EIP 1155: ERC-1155 Multi Token Standard Source

AuthorWitek Radomski, Andrew Cooke, Philippe Castonguay, James Therien, Eric Binet
Discussions-Tohttps://github.com/ethereum/EIPs/issues/1155
StatusDraft (review ends 2019-03-28)
TypeStandards Track
CategoryERC
Created2018-06-17
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 (for example, 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 parameter is contained in each function’s parameters and 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 the ERC1155 and ERC165 interfaces.

pragma solidity ^0.5.8;

/**
    @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.
        Operator MUST be msg.sender.
        When minting/creating tokens, the `_from` field MUST be set to `0x0`
        When burning/destroying tokens, the `_to` field MUST be set to `0x0`
        The total value transferred from address 0x0 minus the total value transferred to 0x0 MAY be used by clients and exchanges to be added to 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.
    */
    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.
        Operator MUST be msg.sender.
        When minting/creating tokens, the `_from` field MUST be set to `0x0`
        When burning/destroying tokens, the `_to` field MUST be set to `0x0`
        The total value transferred from address 0x0 minus the total value transferred to 0x0 MAY be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
        To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_value` of 0.
    */
    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 (absense 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 a JSON file that conforms to the "ERC-1155 Metadata 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.
        @dev MUST emit TransferSingle event on success.
        Caller must be approved to manage the _from account's tokens (see "Approval" section of the standard).
        MUST revert if `_to` is the zero address.
        MUST revert if balance of sender for token `_id` is lower than the `_value` sent.
        MUST revert on any other error.
        After the transfer succeeds, this function MUST check if `_to` is a smart contract (eg. 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, sent in call to `onERC1155Received` on `_to`
    */
    function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;

    /**
        @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call).
        @dev MUST emit TransferBatch event on success.
        Caller must be approved to manage the _from account's tokens (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 of sender for token `_ids` is lower than the respective `_values` sent.
        MUST revert on any other error.
        Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc).
        After all the transfer(s) in the batch succeed, this function MUST check if `_to` is a smart contract (eg. code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).        
        @param _from    Source addresses
        @param _to      Target addresses
        @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, sent in call to `onERC1155BatchReceived` 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 this interface to accept transfers. See “Safe Transfer Rules” for further detail.

pragma solidity ^0.5.8;

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 whether it accepts or rejects the transfer via the prescribed keccak256 generated values.
        Return of any other value than the prescribed keccak256 generated values WILL result in the transaction being reverted.
        Note: The contract address is always the message sender.
        @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("accept_erc1155_tokens()"))`==0x4dc21a2f or `bytes4(keccak256("reject_erc1155_tokens()"))`==0xafed434d
    */
    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 whether it accepts or rejects the transfer via the prescribed keccak256 generated values.
        Return of any other value than the prescribed keccak256 generated values WILL result in the transaction being reverted.
        Note: The contract address is always the message sender.
        @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("accept_batch_erc1155_tokens()"))`==0xac007889 or `bytes4(keccak256("reject_erc1155_tokens()"))`==0xafed434d
    */
    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 safeTransferFrom and safeBatchTransferFrom MUST operate with respect to the ERC1155TokenReceiver, a list of scenarios and rules follows.

Scenarios

Scenario: The recipient is not a contract.

  • onERC1155Received and onERC1155BatchReceived MUST NOT be called on an EOA account.

Scenario: 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: The receiver does not implement the necessary ERC1155TokenReceiver interface function(s).

  • The transfer MUST be reverted with the one caveat below.
    • If the tokens 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: The receiver implements the necessary ERC1155TokenReceiver interface function(s) but returns an unknown value.

  • The transfer MUST be reverted.

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

  • The transfer MUST be reverted.

Scenario: The receiver implements the ERC1155TokenReceiver interface and is the recipient of one and only one balance change in the transaction (eg. safeTransferFrom called).

  • All the balances in the transaction MUST have been updated to match the senders intent before any hook is called on a recipient.
  • The appropriate choice of either onERC1155Received or onERC1155BatchReceived MUST be called on the recipient.
  • The onERC1155Received hook SHOULD be called on the recipient contract and its rules followed.
    • If this hook is called it MUST NOT be called again on the recipient in this transaction.
    • See “onERC1155Received common rules” for further rules that MUST be followed.
  • The onERC1155BatchReceived hook MAY be called on the recipient contract and its rules followed
    • See “onERC1155BatchReceived common rules” for further rules that MUST be followed.

Scenario: The receiver implements the ERC1155TokenReceiver interface and is the recipient of more than one balance change in the transaction (eg. safeBatchTransferFrom called).

  • All the balances in the transaction MUST have been updated to match the senders intent before any hook is called on a recipient.
  • The appropriate choice of either onERC1155Received or onERC1155BatchReceived MUST be called on the recipient.
  • The onERC1155BatchReceived hook SHOULD be called on the recipient contract and its rules followed.
    • If called the arguments MUST contain/list information on every balance change for the recipient (and only the recipient) in this transaction.
    • See “onERC1155BatchReceived common rules” for further rules that MUST be followed.
  • The onERC1155Received hook MAY be called on the recipient contract and its rules followed.
    • If called it MUST be repeatedly called until information has been passed and return value checked for every balance change for the recipient (and only the recipient) in this transaction.
    • See “onERC1155Received common rules” for further rules that MUST be followed.

Rules

onERC1155Received common rules:

  • If this hook is called onERC1155BatchReceived MUST NOT also be called on the recipient in this transaction.
  • The _operator argument MUST be the address of the account/contract that initiated the transfer (i.e. 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 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 extra information provided by the sender (if any) for a transfer.
  • The destination/to contract MAY accept an increase of its balance by returning the acceptance magic value bytes4(keccak256("accept_erc1155_tokens()"))
    • If the return value is bytes4(keccak256("accept_erc1155_tokens()")) the transfer MUST be completed, unless other conditions necessitate a revert.
  • The destination/to contract MAY reject an increase of its balance by returning the rejection magic value bytes4(keccack256("reject_erc1155_tokens()")).
    • If the return value is bytes4(keccak256("reject_erc1155_tokens()")) the transaction MUST be reverted.
  • If the return value is anything other than bytes4(keccak256("accept_erc1155_tokens()")) or bytes4(keccack256("reject_erc1155_tokens()")) the transaction MUST be reverted.

onERC1155BatchReceived common rules:

  • If this hook is called onERC1155Received MUST NOT also be called on the recipient in this transaction.
  • If this hook is called it MUST NOT be called again on the recipient in this transaction.
  • The _operator argument MUST be the address of the account/contract that initiated the transfer (i.e. 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 extra information provided by the sender (if any) for a transfer.
  • The destination/to contract MAY accept an increase of its balance by returning the acceptance magic value bytes4(keccak256("accept_batch_erc1155_tokens()"))
    • If the return value is bytes4(keccak256("accept_batch_erc1155_tokens()")) the transfer MUST be completed, unless other conditions necessitate a revert.
  • The destination/to contract MAY reject an increase of its balance by returning the rejection magic value bytes4(keccack256("reject_erc1155_tokens()")).
    • If the return value is bytes4(keccak256("reject_erc1155_tokens()")) the transaction MUST be reverted.
  • If the return value is anything other than bytes4(keccak256("accept_batch_erc1155_tokens()")) or bytes4(keccack256("reject_erc1155_tokens()")) the transaction MUST be reverted.

Implementation specific transfer api rules:

  • If implementation specific api functions are used to transfer 1155 tokens to a contract the appropriate hook(s) MUST still be called with the same rules as if safeTransferFrom/safeBatchTransferFrom was used.
  • The appropriate events MUST be correctly emitted as if safeTransferFrom/safeBatchTransferFrom was used.
A solidity example of the keccak256 generated constants for the return magic is:
  • bytes4 constant public ERC1155_REJECTED = 0xafed434d; // keccak256(“reject_erc1155_tokens()”)
  • bytes4 constant public ERC1155_ACCEPTED = 0x4dc21a2f; // keccak256(“accept_erc1155_tokens()”)
  • bytes4 constant public ERC1155_BATCH_ACCEPTED = 0xac007889; // keccak256(“accept_batch_erc1155_tokens()”)

Compatibility with other standards

There have been requirements during the design discussions to have this standard be compatible with older standards when sending to contract addresses, specifically ERC721 at time of writing. To cater for this there is some leeway with the rejection logic should a contract not implement the ERC1155TokenReceiver as per “Safe Transfer Rules” section above, specifically the scenario “The receiver does not implement the necessary ERC1155TokenReceiver interface function(s)”. In that particular scenario if the 1155 implementation is also a hybrid implementation of another token standard, it MAY now follow the secondary standard’s rules when transferring token(s) to a contract address.

Note that a pure implementation of a single standard is recommended rather than a hybrid solution, but an example of a hybrid 1155+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 1155 transfer events MUST still be emitted. This is so the balances can still be determined via events alone as per 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 large number of tokens to use the same on-chain string by defining a URI once, for a large collection of tokens. 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.

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.

Metadata Extensions

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

Changes to the URI MUST emit the URI event if the change can be expressed with an event (i.e. it isn’t dynamic). If the optional ERC1155Metadata_URI extension is included, the ‘uri’ function SHOULD be used to retrieve values for which no event was emitted. The function MUST return the same value as the event if it was emitted.

pragma solidity ^0.5.8;

/**
    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 may point to a JSON file that conforms to the "ERC-1155 Metadata 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.

{
    "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 (DRAFT) is suggested. The counterpart isAprrovedForAll provides introspection into 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.

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, or destroyed.

Non-Fungible Tokens

The following strategy is an example of how to mix fungible and non-fungible tokens together in the same contract. The top 128 bits of the uint256 _id parameter in any ERC-1155 function could represent the base token ID, while the bottom 128 bits might be used for any extra data passed to the contract.

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 particular NFT within that set, _id could be passed as <uint128: base token 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.

Example of split ID bits

uint256 baseToken = 12345 << 128;
uint128 index = 50;

balanceOf(baseToken, msg.sender); // Get balance of the base token
balanceOf(baseToken + index, msg.sender); // Get balance of the Non-Fungible token index

References

Standards

Implementations

Articles & Discussions

Copyright and related rights waived via CC0.