Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article covers ERC5216, a proposed extension to ERC1155 that enables more granular token approvals through approve.

This article translates, summarizes, and expands on the proposal below.

As of September 3, 2023, ERC5216 was at the Last Call stage.

Overview

EIP1155 provides a standard interface for efficiently managing multiple token units with the same token ID.

For more on ERC1155, see the following article.

https://chaldene.net/erc1155

Motivation

The proposed standard enables more granular approvals based on a token identifier (id) and an amount. Whereas ERC721 identifies individual NFTs by ID, ERC1155 associates a quantity with each ID.

For more on ERC721, see the following article.

https://chaldene.net/erc721

For more on ERC1155, see the following article.

https://chaldene.net/erc1155

Programming errors or malicious operations on a blockchain can result in permanent loss of funds, so transactions must be executed securely. ERC1155 uses setApprovalForAll to let an operator manage all of an owner's tokens in that contract, across token IDs.

The setApprovalForAll function lets an owner grant a specified address (the operator) permission to manage the owner's tokens collectively.

Suppose Alice, the owner of an NFT (non-fungible token), wants to list her token on the NFT marketplace OpenSea. Alice can use setApprovalForAll to authorize OpenSea's operator to manage her NFTs.

solidity
// NFTの所有者
address public owner = msg.sender;

// NFTマーケットプレイスのアドレス
address public marketplace = 0x...; // ダミーアドレス

// NFTのトークンID
uint256 public tokenId = 123;

// Marketplaceに対してトークンの操作権限を一括で与える
function grantPermissionToMarketplace() public {
    // ownerがmarketplaceに対して操作権限を一括で与える
    approve(marketplace, true);
}

// 操作権限を取り消す
function revokePermissionFromMarketplace() public {
    // ownerがmarketplaceに対して操作権限を取り消す
    approve(marketplace, false);
}

// アドレスに対して操作権限を一括で与える関数
function approve(address operator, bool approval) private {
    // ERC-1155のsetApprovalForAll関数を呼び出す
    IERC1155(tokenContractAddress).setApprovalForAll(operator, approval);
}

In this example, Alice calls grantPermissionToMarketplace to grant the marketplace operator permission to manage her NFTs so that she can list them on OpenSea. When an NFT is sold, the marketplace can use the approval granted by Alice to transfer the token. When the permission is no longer needed, Alice can call revokePermissionFromMarketplace to revoke the marketplace's approval.

This approach does not provide sufficiently granular permissions to minimize the trust placed in an operator. The proposal combines ideas from ERC20 and ERC721 to allow owners to approve a specified quantity of tokens of a particular id for a third party, such as a marketplace.

For more on ERC20, see the following article.

https://chaldene.net/erc20

Specification

Contracts implementing this EIP must implement the IERC1155ApprovalByAmount interface.

Interface Implementation

javascript
/**
 * @title ERC-1155 Approval By Amount Extension
 * Note: the ERC-165 identifier for this interface is 0x1be07d74
 */
interface IERC1155ApprovalByAmount is IERC1155 {

    /**
     * @notice Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `id` and with an amount: `amount`.
     */
    event ApprovalByAmount(address indexed account, address indexed operator, uint256 id, uint256 amount);

    /**
     * @notice Grants permission to `operator` to transfer the caller's tokens, according to `id`, and an amount: `amount`.
     * Emits an {ApprovalByAmount} event.
     *
     * Requirements:
     * - `operator` cannot be the caller.
     */
    function approve(address operator, uint256 id, uint256 amount) external;

    /**
     * @notice Returns the amount allocated to `operator` approved to transfer `account`'s tokens, according to `id`.
     */
    function allowance(address account, address operator, uint256 id) external view returns (uint256);
}
  • approve(address operator, uint256 id, uint256 amount) must be public or external.
  • allowance(address account, address operator, uint256 id) must be public or external and view.
  • safeTransferFrom, defined in EIP1155, must satisfy the following conditions.
    • A transfer must not revert for lack of approval if the user has approved a sufficient token amount for msg.sender. Other ERC1155 validity checks still apply.
    • When an operator relies on amount-based approval rather than setApprovalForAll, the amount transferred must be deducted from the approved amount.

In the delegated-transfer case described here, msg.sender is an address authorized by the token owner to transfer tokens, rather than the owner. An operator approved through setApprovalForAll can manage all of the owner's tokens in the contract. Otherwise, it can manage only the approved portion of the owner's tokens, if any approval exists. A transfer based on an amount allowance can therefore proceed only up to the approved quantity.

  • safeBatchTransferFrom requires the following additional condition.
    • For an operator relying on amount-based approval, check whether the requested amount is approved for every id being transferred.

The safeBatchTransferFrom function safely transfers multiple tokens in a single operation. Consider a concrete example.

Suppose Bob wants to transfer several different NFTs (non-fungible tokens) that he owns to Alice in one operation.

solidity
// ERC-1155のトークンコントラクトアドレス
address public tokenContractAddress = 0x...; // ダミーアドレス

// Bobのアドレス
address public bob = msg.sender;

// Aliceのアドレス
address public alice = 0x...; // ダミーアドレス

// 転送するトークンの情報
uint256[] public tokenIds = [1, 2, 3]; // 仮のトークンID
uint256[] public amounts = [1, 1, 1]; // 各トークンの数量

// BobがAliceにトークンを一括で転送する
function transferTokensToAlice() public {
    // ERC-1155のsafeBatchTransferFrom関数を呼び出す
    IERC1155(tokenContractAddress).safeBatchTransferFrom(bob, alice, tokenIds, amounts, "");
}

In the example above, Bob calls transferTokensToAlice to transfer multiple NFTs to Alice in one operation. The safeBatchTransferFrom function transfers the specified amounts of the specified token IDs from Bob's address to Alice's address.

safeBatchTransferFrom is useful when transferring several different tokens together. A successful call safely transfers the specified quantities of the specified token IDs.

  • When an amount-based approval is set, emit the ApprovalByAmount event.
  • supportsInterface returns true when called with 0x1be07d74.

Additional Considerations

The name "EIP-1155 Approval By Amount Extension" was chosen to describe this EIP succinctly. The EIP extends ERC1155 to let users approve an operator for a specified quantity of a particular token ID.

Approving and revoking token permissions in a manner similar to EIP20 gives users more direct control over their tokens.

  • With approve, a user can authorize a particular operator to use a specified quantity of tokens for each token ID.
  • With allowance, a user can check the quantity approved for a particular operator for each token ID.

The name reflects the fact that this proposed approval mechanism for EIP1155 draws on the existing ideas in EIP20, making token management easier to understand. Users can manage the operations permitted on their own tokens more precisely.

Backward Compatibility

The standard is compatible with EIP1155.

Reference Implementation

The following is the reference implementation.

javascript
// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.15;

import "IERC1155.sol";
import "ERC1155.sol";

/**
 * @title ERC-1155 Approval By Amount Extension
 * Note: the ERC-165 identifier for this interface is 0x1be07d74
 */
interface IERC1155ApprovalByAmount is IERC1155 {

    /**
     * @notice Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `id` and with an amount: `amount`.
     */
    event ApprovalByAmount(address indexed account, address indexed operator, uint256 id, uint256 amount);

    /**
     * @notice Grants permission to `operator` to transfer the caller's tokens, according to `id`, and an amount: `amount`.
     * Emits an {ApprovalByAmount} event.
     *
     * Requirements:
     * - `operator` cannot be the caller.
     */
    function approve(address operator, uint256 id, uint256 amount) external;

    /**
     * @notice Returns the amount allocated to `operator` approved to transfer `account`'s tokens, according to `id`.
     */
    function allowance(address account, address operator, uint256 id) external view returns (uint256);
    
}

/**
 * @dev Extension of {ERC1155} that allows you to approve your tokens by amount and id.
 */
abstract contract ERC1155ApprovalByAmount is ERC1155, IERC1155ApprovalByAmount {

    // Mapping from account to operator approvals by id and amount.
    mapping(address => mapping(address => mapping(uint256 => uint256))) internal _allowances;

    /**
     * @dev See {IERC1155ApprovalByAmount}
     */
    function approve(address operator, uint256 id, uint256 amount) public virtual {
        _approve(msg.sender, operator, id, amount);
    }

    /**
     * @dev See {IERC1155ApprovalByAmount}
     */
    function allowance(address account, address operator, uint256 id) public view virtual returns (uint256) {
        return _allowances[account][operator][id];
    }

    /**
     * @dev safeTransferFrom implementation for using ApprovalByAmount extension
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) public override(IERC1155, ERC1155) {
        require(
            from == msg.sender || isApprovedForAll(from, msg.sender) || allowance(from, msg.sender, id) >= amount,
            "ERC1155: caller is not owner nor approved nor approved for amount"
        );
        unchecked {
            _allowances[from][msg.sender][id] -= amount;
        }
        _safeTransferFrom(from, to, id, amount, data);
    }

    /**
     * @dev safeBatchTransferFrom implementation for using ApprovalByAmount extension
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) public virtual override(IERC1155, ERC1155) {
        require(
            from == msg.sender || isApprovedForAll(from, msg.sender) || _checkApprovalForBatch(from, msg.sender, ids, amounts),
            "ERC1155: transfer caller is not owner nor approved nor approved for some amount"
        );
        _safeBatchTransferFrom(from, to, ids, amounts, data);
    }

    /**
     * @dev Checks if all ids and amounts are permissioned for `to`. 
     *
     * Requirements:
     * - `ids` and `amounts` length should be equal.
     */
    function _checkApprovalForBatch(
        address from, 
        address to, 
        uint256[] memory ids,
        uint256[] memory amounts
    ) internal virtual returns (bool) {
        uint256 idsLength = ids.length;
        uint256 amountsLength = amounts.length;

        require(idsLength == amountsLength, "ERC1155ApprovalByAmount: ids and amounts length mismatch");
        for (uint256 i = 0; i < idsLength;) {
            require(allowance(from, to, ids[i]) >= amounts[i], "ERC1155ApprovalByAmount: operator is not approved for that id or amount");
            unchecked { 
                _allowances[from][to][ids[i]] -= amounts[i];
                ++i; 
            }
        }
        return true;
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens by id and amount.
     * Emits a {ApprovalByAmount} event.
     */
    function _approve(
        address owner,
        address operator,
        uint256 id,
        uint256 amount
    ) internal virtual {
        require(owner != operator, "ERC1155ApprovalByAmount: setting approval status for self");
        _allowances[owner][operator][id] = amount;
        emit ApprovalByAmount(owner, operator, id, amount);
    }
}

contract ExampleToken is ERC1155ApprovalByAmount {
    constructor() ERC1155("") {}

    function mint(address account, uint256 id, uint256 amount, bytes memory data) public {
        _mint(account, id, amount, data);
    }

    function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public {
        _mintBatch(to, ids, amounts, data);
    }
}

approve

javascript
function approve(address operator, uint256 id, uint256 amount) public virtual {
    _approve(msg.sender, operator, id, amount);
}

Overview

A function that lets an owner authorize a particular operator to use a specified quantity of a particular token ID.

Details

An owner uses this function to grant an operator permission to use tokens. It sets the amount that the specified operator may use for a particular token ID. The function calls _approve internally to perform the approval.

Parameters

  • operator
    • The address (operator) receiving permission to manage the tokens.
  • id
    • The ID of the token for which permission is granted.
  • amount
    • The quantity of tokens the operator is authorized to manage.

allowance

javascript
function allowance(address account, address operator, uint256 id) public view virtual returns (uint256) {
    return _allowances[account][operator][id];
}

Overview

A function that retrieves the approved quantity for a specific token ID, account, and operator.

Details

The function returns the approved token amount for the specified account and operator for a particular token ID. Users can therefore determine how much permission an operator has for a particular token.

Parameters

  • account
    • The address of the account whose approval information is being queried.
  • operator
    • The address of the operator authorized by the account.
  • id
    • The token ID whose approval information is being queried.

Return value

An integer indicating the approved token quantity for the specified account, operator, and token ID.


safeTransferFrom

javascript
function safeTransferFrom(
    address from,
    address to,
    uint256 id,
    uint256 amount,
    bytes memory data
) public override(IERC1155, ERC1155) {
    require(
        from == msg.sender || isApprovedForAll(from, msg.sender) || allowance(from, msg.sender, id) >= amount,
        "ERC1155: caller is not owner nor approved nor approved for amount"
    );
    unchecked {
        _allowances[from][msg.sender][id] -= amount;
    }
    _safeTransferFrom(from, to, id, amount, data);
}

Overview

A function that performs safe token transfers using the ApprovalByAmount extension.

Details

The function transfers tokens if one of the following authorization conditions is satisfied.

  • from is msg.sender, or from has granted msg.sender operator approval through isApprovedForAll.
  • from has granted msg.sender a sufficient allowance for the specified id and amount.

The reference code subtracts the transfer amount from the operator's allowance before the transfer. It then calls _safeTransferFrom to perform the safe token transfer.

There is a security-relevant discrepancy in the historical sample above: it subtracts the allowance unconditionally inside an unchecked block, even for the owner or an operator approved for all tokens. If the amount exceeds the allowance, the subtraction can wrap around. The example is preserved as written; a production implementation must only spend the allowance when the transfer actually relies on amount-based approval.

Parameters

  • from
    • The token owner's address.
  • to
    • The recipient address.
  • id
    • The token ID to transfer.
  • amount
    • The quantity of tokens to transfer.
  • data
    • Arbitrary additional data.

safeBatchTransferFrom

javascript
function safeBatchTransferFrom(
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) public virtual override(IERC1155, ERC1155) {
    require(
        from == msg.sender || isApprovedForAll(from, msg.sender) || _checkApprovalForBatch(from, msg.sender, ids, amounts),
        "ERC1155: transfer caller is not owner nor approved nor approved for some amount"
    );
    _safeBatchTransferFrom(from, to, ids, amounts, data);
}

Overview

A function that performs safe batch token transfers using the ApprovalByAmount extension.

Details

The function transfers multiple tokens in one operation if one of the following authorization conditions is satisfied.

  • from is msg.sender, or from has granted msg.sender operator approval through isApprovedForAll.
  • from has granted msg.sender a sufficient allowance for each requested token ID and amount.

When the transfer relies on amount-based approval, the operator's approved amounts are deducted in the batch approval check before the transfer. The function then calls _safeBatchTransferFrom to perform the safe batch transfer.

Parameters

  • from
    • The token owner's address.
  • to
    • The recipient address.
  • ids
    • An array of token IDs to transfer.
  • amounts
    • An array of token quantities to transfer.
  • data
    • Arbitrary additional data.

_checkApprovalForBatch

javascript
function _checkApprovalForBatch(
    address from, 
    address to, 
    uint256[] memory ids,
    uint256[] memory amounts
) internal virtual returns (bool) {
    uint256 idsLength = ids.length;
    uint256 amountsLength = amounts.length;

    require(idsLength == amountsLength, "ERC1155ApprovalByAmount: ids and amounts length mismatch");
    for (uint256 i = 0; i < idsLength;) {
        require(allowance(from, to, ids[i]) >= amounts[i], "ERC1155ApprovalByAmount: operator is not approved for that id or amount");
        unchecked { 
            _allowances[from][to][ids[i]] -= amounts[i];
            ++i; 
        }
    }
    return true;
}

Overview

A function that checks whether the specified token IDs and quantities are approved for a batch token transfer.

Details

During a batch token transfer, this function checks the approval for each specified token ID and quantity against the allowances granted by from to the operator identified by its to parameter. It checks that the ids and amounts arrays contain the same number of elements and verifies the allowance for each token. Once each approval is validated, the function deducts the corresponding amount.

Parameters

  • from
    • The token owner's address.
  • to
    • The address whose allowances are checked; the caller passes the operator (msg.sender), not necessarily the final token recipient.
  • ids
    • An array of token IDs to transfer.
  • amounts
    • An array of token quantities to transfer.

Return value

Returns true if the token IDs and amounts are properly approved.


_approve

javascript
function _approve(
    address owner,
    address operator,
    uint256 id,
    uint256 amount
) internal virtual {
    require(owner != operator, "ERC1155ApprovalByAmount: setting approval status for self");
    _allowances[owner][operator][id] = amount;
    emit ApprovalByAmount(owner, operator, id, amount);
}

Overview

A function that lets an owner approve an operator for a specific token ID and quantity.

Details

The specified owner address, owner, grants the operator address, operator, approval for the specified quantity of a particular token ID. However, an owner cannot approve itself as an operator. The approval is recorded in the _allowances mapping, and the ApprovalByAmount event is emitted.

Parameters

  • owner
    • The token owner's address.
  • operator
    • The address of the operator that manages the tokens.
  • id
    • The token ID being approved.
  • amount
    • The quantity of tokens being approved.

Security Considerations

Users of this EIP should carefully consider the number of tokens they approve for an operator and consider revoking unused allowances.

Users should manage token allowances carefully and revoke unnecessary permissions.

Citation

Iván Mañús (@ivanmmurciaua), Juan Carlos Cantó (@EscuelaCryptoES), "ERC-5216: EIP-1155 Approval By Amount Extension [DRAFT]," Ethereum Improvement Proposals, no. 5216, July 2022. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-5216.

Conclusion

This article covered ERC5216, an extension to ERC1155 that provides more granular token approvals through approve.

If you have questions, feel free to contact me by direct message on Twitter.

Twitter @cardene777