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).
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.
本协议各个函数中的参数”_id”表示交易中的某个通证或通证种类。
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.
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.
部署ERC-1155标准的智能合约必须实现ERC1155接口定义的所有函数。
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.
Smart contracts MUST implement all of the functions in the ERC1155TokenReceiver interface to accept transfers. See “Safe Transfer Rules” for further detail.
智能合约必须实现ERC1155TokenReceiver接口中所有定义的函数。更多细节请参看“Safe Transfer Rules”。
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.
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.
Scenario#3 : The receiver does not implement the necessary ERC1155TokenReceiver interface function(s).
场景3:作为接收者的合约没有实现ERC1155TokenReceiver接口中相应的函数
· 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.
如果交易的通证是用其它合约标准实现的并且通证的实现代码中包含标准和非标准函数,则该交易可以遵循该通证的合约标准而不是ERC1155标准。详细信息请参看“Compatibility with other standards “。
Scenario#4 : The receiver implements the necessary ERC1155TokenReceiver interface function(s) but returns an unknown value.
场景4:接收合约实现了ERC1155TokenReceiver中相应的接口函数但返回一个未知值。
· The transfer MUST be reverted.
该笔交易必须被回滚。
Scenario#5 : The receiver implements the necessary ERC1155TokenReceiver interface function(s) but throws an error.
场景5:接收合约实现了ERC1155TokenReceiver中相应的接口函数但抛出错误。
· 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).
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.
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.
Scenario#9 : You are transferring tokens via a non-standard API call i.e. an implementation specific API and NOT safeTransferFrom or safeBatchTransferFrom.
。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.
· MUST emit the TransferSingle event to reflect the balance change (see “TransferSingle and TransferBatch event rules” section).
必须触发TransferSingle事件以反映账户余额的变化(请参看“TransferSingle and TransferBatch event rules”章节)
· 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.
· MUST emit TransferSingle or TransferBatch event(s) such that all the balance changes are reflected (see “TransferSingle and TransferBatch event rules” section).
必须触发TransferSingle或TransferBatch事件以反映所有账户余额的变化(请参看“TransferSingle and TransferBatch event rules”章节)
· 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).
当上述条件满足时,safeBatchTransferFrom函数必须检查参数“_to”是否是一个智能合约地址(比如检查code size是否大于0),如果是,就必须在参数“_to”所指向的智能合约上调用onERC1155Received或onERC1155BatchReceived并执行相应的操作(请参看“onERC1155Received and onERC1155BatchReceived rules”章节)。
。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.
。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.
。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.
。When minting/creating tokens, the _from argument MUST be set to 0x0 (i.e. zero address).
当挖矿/创建通证时,参数“_from”的值必须设为“0x0”(即零地址)。
See “Minting/creating and burning/destroying rules”.
请参看“Minting/creating and burning/destroying rules”
。When burning/destroying tokens, the _to argument MUST be set to 0x0 (i.e. zero address).
当消除/销毁通证时,参数”_to”的值必须设为“0x0”(即零地址)。
See “Minting/creating and burning/destroying rules”.
请参看“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.
· 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.
。The set of all calls to onERC1155Received and onERC1155BatchReceived describes all balance changes that occurred during the transaction in the order submitted.
· The _from argument MUST be the address of the holder whose balance is decreased.
参数“_from”所指定的地址在交易发生后,余额减少。
。_from MUST be 0x0 for a mint.
挖矿时参数“_from”的值必须为“0x0”。
· The _ids argument MUST be the list of tokens being transferred.
参数“_ids”表示交易转账的通证列表。
· 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 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.
。The set of all calls to onERC1155Received and onERC1155BatchReceived describes all balance changes that occurred during the transaction in the order submitted.
。It MUST return the constant value true if 0x4e2312e0 is passed through the interfaceID argument. This signifies ERC-1155 ERC1155TokenReceiver support.
· 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: 特定转账API函数的实现规则
· 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.
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.
注意:如果接收方地址无法接收ERC-1155通证,则这种操作可能会导致转账的通证永久丢失。
· The above example is not exhaustive but illustrates the major points (and shows that most are shared with safeTransferFrom and safeBatchTransferFrom):
。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.
所有被调用并且被实现的ERC1155TokenReceiver接口函数,其返回值都必须被合理设置。
。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”).
仅当调用非标准函数时才允许通证被发送给一个没有实现ERC1155TokenReceiver接口函数的智能合约。在这种情况下,safeTransferFrom和safeBatchTransferFrom必须回滚交易(除非它包含标准和非标准的接口实现,详细信息请参看“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.
(单币种或多币种)挖矿时,“TransferSingle and TransferBatch event rules”章节中所描述的规则必须遵循,此时参数”_from”必须设为“0x0”(即零地址)以标识此交易为挖矿。
· 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.
(单币种或多币种)销毁时,“TransferSingle and TransferBatch event rules”章节中所描述的规则也必须遵循,此时参数”_to”必须设为“0x0”(即零地址)以标识此交易为销毁。
。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.
综上所述,挖矿/创建和消除/销毁通证的操作是特殊的转账交易,有可能通过除safeTransferFrom和safeBatchTransferFrom以外的用户自定义函数实现。当用户用自定义的函数实现时,必须遵循“Implementation specific transfer API rules”章节所定义的规则。
。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).
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)”.
在制定本标准时,与现有标准尤其是ERC-721标准兼容一直是讨论的议题。当一个合约没有遵循ERC1155TokenReceiver的“Safe Transfer Rules”规则时,尤其是没有遵循其“场景3:接收者没有实现ERC1155TokenReceiver接口中相应的函数”的规则时,对交易回滚的处理可以有一些灵活的手法。
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:
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.
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.
通证的ID必须仅仅包含小写字母和数字【0-9a-f】并且不带前缀“0x”。
· The string format of the substituted hexadecimal ID MUST be leading zero padded to 64 hex characters length if necessary.
通证的ID必须包含64个十六进制字符,若字符数没有64个,则在字符串前面全部用0填充。
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.
。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.
合约的实现代码可以在挖矿操作中触发URI事件,但这不是强制性的。
在挖矿时,如果没有事件触发,用户或许仍然可以从URI函数中获取元数据URI。
· The uri function SHOULD be used to retrieve values if no event was emitted.
如果没有事件触发,要获取数据就要调用URI函数。
· The uri function MUST return the same value as the latest event for an _id if it was emitted.
对同一”_id”,URI函数的返回值必须和最近一次触发的事件返回值一样。
· 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.
ERC-1155 Metadata URI JSON Schema ERC-1155元数据 URI JSON框架
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.
通证的ID必须仅仅包含小写字母和数字【0-9a-f】并且不带前缀“0x”。
· The string format of the substituted hexadecimal ID MUST be leading zero padded to 64 hex characters length if necessary.
通证的ID必须包含64个十六进制字符,若字符数没有64个,则在字符串前面全部用0填充。
An example of an ERC-1155 Metadata JSON file follows. The properties array proposes some SUGGESTED formatting for token-specific display properties and metadata.
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.
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.
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.
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.
The standard supports safeTransferFrom and onERC1155Received functions because they are significantly cheaper for single token-type transfers, which is arguably a common use case.
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.
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.
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.
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.
建议用户和钱包项目方要进行批量转账时,对待转账的所有token ID和每个ID对应的通证数量进行排序(升序排列)。因为ERC-1155标准对进行了排序的通证进行批量转账时会显著降低gas耗费。详细信息请参看“Horizon Games - Multi-Token Standard”章节中的“打包余额(packed balance)”实例。
Batch Balance 批量账户余额
The balanceOfBatch function allows clients to retrieve balances of multiple owners and token IDs with a single call.
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.
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.
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.
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.
ERC-1155参考案例展示了如何划分ID的数位用途。
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.