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 introduces ERC721A from the ground up.

As its name suggests, ERC721A is related to ERC721. It was developed by Azuki, a well-known NFT project, and has been adopted by other prominent NFT projects in Japan and abroad.

Although its name differs from ERC721 by just one letter, understanding the implementation takes some time. We will work through the concepts and code step by step.

The following is the study session held on February 17, 2023, where I presented these slides.

What is ERC721?

ERC721 overview

Before learning ERC721A, it helps to understand ERC721 itself.

If you are unfamiliar with ERC721, the following article introduces it in detail.

/articles/0570a8d05bc7c9b9593f

What is ERC721Enumerable?

ERC721Enumerable overview

ERC721Enumerable provides a way to retrieve a list of ERC721 tokens owned by a particular address.

For further background, see the following articles.

/articles/0570a8d05bc7c9b9593f

/articles/0570a8d05bc7c9b9593f

What is ERC721A?

ERC721A overview

Overview

Even if you have heard of ERC721, you may not be familiar with ERC721A.

ERC721A is an ERC721 implementation developed by the popular NFT project Azuki.

At the time of writing, it had been adopted by prominent NFT projects in Japan and abroad.

NFT projects

  • NEO TOKYO PUNKS
  • NEO Samurai Mokeys
  • Moonbirds
  • Dooplicator
  • RTFKT
  • goblintown
  • adidas IMPOSSIBLE BOX

In short, ERC721A reduces the gas cost of minting multiple NFTs while making it possible to retrieve the tokens owned by an address.

The original article describes this as retaining the ERC721Enumerable interface. More precisely, the version examined below does not advertise IERC721Enumerable support in supportsInterface; the optional ERC721AQueryable extension provides ownership queries such as tokensOfOwner.

Features

The following three characteristics are central to ERC721A.

ERC721A features

  • Retains owner-token enumeration functionality through queries.
  • Eliminates redundant storage used for ERC721Enumerable-style enumeration.
  • Updates ERC721 token balances and ownership data in batches.

We will examine each of these features using OpenZeppelin's ERC721 and ERC721Enumerable implementations as the point of comparison.

ERC721Enumerable-style enumeration functionality

The previous section described ERC721Enumerable as a way to retrieve the ERC721 tokens owned by a particular address.

Instead of maintaining the same enumeration data in storage, ERC721A can achieve equivalent owner-token discovery by scanning the tokens and identifying those belonging to the address. In the version presented in this article, this is provided by ERC721AQueryable rather than the base ERC721A contract implementing the full IERC721Enumerable interface.

Eliminating redundant ERC721Enumerable storage

Adding or updating data in smart contract storage consumes gas.

With ERC721Enumerable, minting or transferring each ERC721 token requires multiple storage updates.

See the following article for the data that is updated.

/articles/0570a8d05bc7c9b9593f

ERC721Enumerable optimizes reads by spending more gas on writes.

However, off-chain read calls do not incur transaction fees, and reads are generally less costly than writes when executed on-chain. Paying for extra storage updates is therefore not always the ideal trade-off.

Each ERC721 token also has a unique token ID, which enables an alternative implementation, as explained in the following section.

Updating token balances and ownership data in batches

Suppose you own two tokens and want to purchase three more.

With ERC721Enumerable, values such as the owner's balance are updated one token at a time, incurring gas costs.

2→3→4→5

Updating the value only once, as shown below, can save gas.

2→5

This is a relatively straightforward concept. However, the ordinary OpenZeppelin ERC721 implementation discussed here does not expose a batch mint operation that mints multiple NFTs in a single transaction.

Updating ownership data in a single operation also saves gas.

Again, imagine that you own two tokens and want to purchase three more.

With conventional ERC721, the ownership data for each token must be updated individually.

If ownership could instead be recorded as "the address 0xabc123… owns token IDs 50–55," it would reduce the number of storage writes.

This particular optimization is effective when several tokens are minted together. When tokens are minted one at a time, it does not provide the same batch-related saving.

ERC721A gas costs

Let's compare the gas costs of using ERC721A and ERC721Enumerable.

The charts below come from Azuki's official website.

https://www.azuki.com/erc721a

With ERC721Enumerable, the gas cost increases substantially with each token minted.

In this comparison, ERC721A uses less than half as much gas.

The official page also presents the figures converted into US dollars.

https://www.azuki.com/erc721a

These prices reflect the conditions at the time of writing. They illustrate the substantial savings achievable with ERC721A.

How ERC721A works

How ERC721A works

Now that we have covered the overview and features of ERC721A, let's examine how it works in more detail.

The diagrams in this section were heavily inspired by the following article.

What does Azuki's NFT implementation ERC721A do?

Minting tokens

ERC721

As explained above, ERC721A can update ownership data in batches when minting tokens.

In ERC721, each token is associated with its owner, as shown below.

ERC721 ownership records

When several consecutive tokens are minted, recording the owner of each token separately incurs storage costs for every token.

Here, consecutive tokens means tokens with successive token IDs, such as 1, 2, and 3.

ERC721A proposes a way to improve this part of the implementation.

ERC721A

When minting consecutive tokens, ERC721A records ownership data only for the first token ID of the batch.

ERC721A batch ownership record

This combines what would otherwise be an ownership update for every ERC721 token into essentially a single storage update.

The number of tokens owned by an address can also be updated at once, for example from 2→5.

If the same owner receives tokens with IDs 1, 2, 5, and 6 in separate consecutive batches, ownership is recorded as illustrated below.

ERC721A ownership across separate batches

How do we retrieve this data?

Although it is easy to retrieve the ownership data stored explicitly, we still need a way to determine the owners of consecutive tokens without their own initialized ownership entries.

Retrieving tokens

Let's look at how to retrieve the tokens owned by an address.

The basic approach is to scan all the tokens.

As shown below, the query examines the minted tokens one by one. When it encounters an ownership record for the requested address, it collects the token IDs belonging to that address until the ownership changes, repeating the process across the collection.

Retrieving tokens owned by an address

This operation does not update storage, so it avoids the cost of storage writes. Nevertheless, the work increases with the number of tokens, which can become significant for large collections, particularly for on-chain calls.

Updating ownership

Finally, let's examine what happens when the owner of a token changes.

Suppose the token with ID 3 is transferred to another address.

Transferring token ID 3

In addition to recording the new owner, the contract may need to initialize the ownership record for token ID 4.

If only token ID 3 were updated, the ownership lookup in the diagram below would incorrectly identify 0xC… as the owner of tokens 4 and 5.

Incorrect ownership if the next boundary is not initialized

Updating the records for token IDs 3 and 4 preserves the ownership of the remaining tokens.

The final result looks like this.

Correct ownership after updating the batch boundary

Examining the ERC721A code

ERC721A code overview

In this section, we will examine the actual ERC721A code.

The original source is available below.

chiru-labs - ERC721A

Parts of ERC721A resemble conventional ERC721 code, so the explanations of those parts are brief.

For a particular function, use Command + F to search for its name.

The following code excerpts reflect the version discussed in the original 2023 article. Later versions may differ.

Struct

javascript
struct TokenApprovalRef {
    address value;
}

Stores the address approved to transfer a token.

The struct can be customized to store additional information beyond the address.

STORAGE

_currentIndex

javascript
uint256 private _currentIndex;

Stores the token ID of the next token to be minted.

It advances as tokens are minted.

_burnCounter

javascript
uint256 private _burnCounter;

Stores the number of burned tokens.

It increments each time a token is burned.

_name, _symbol

javascript
string private _name;
string private _symbol;

Store the name and symbol of the ERC721 collection.

_packedOwnerships

javascript
mapping(uint256 => uint256) private _packedOwnerships;

This mapping associates token IDs with packed ownership data.

As described earlier, an empty ownership entry for a token ID does not necessarily mean that the token has no owner.

For a newly minted consecutive batch, ownership data is initially recorded only at the smallest token ID of the batch.

The stored values have the following layout.

javascript
// - [0..159]   `addr`
// - [160..223] `startTimestamp`
// - [224]      `burned`
// - [225]      `nextInitialized`
// - [232..255] `extraData`

These fields are packed into a single 256-bit value.

Bit shifts and bitwise operations extract individual fields, such as the owner address and whether the token has been burned.

_packedAddressData

javascript
mapping(address => uint256) private _packedAddressData;

This mapping uses the token owner's address as the key. The stored 256-bit value combines information such as the owner's token balance and the number of tokens the address has minted.

The layout is shown below.

javascript
// - [0..63]    `balance`
// - [64..127]  `numberMinted`
// - [128..191] `numberBurned`
// - [192..255] `aux`

_tokenApprovals

javascript
mapping(uint256 => TokenApprovalRef) private _tokenApprovals;

Uses a token ID as the key and stores a TokenApprovalRef struct containing the address approved to transfer that token.

_operatorApprovals

javascript
mapping(address => mapping(address => bool)) private _operatorApprovals;

Uses the owner's address as the key and maps operator addresses to whether they have permission to transfer the owner's tokens.

Conventional ERC721 implementations define a similar mapping.

CONSTRUCTOR

javascript
constructor(string memory name_, string memory symbol_) {
    _name = name_;
    _symbol = symbol_;
    _currentIndex = _startTokenId();
}

The constructor executes once when the contract is deployed.

It takes the token name and symbol as arguments and calls _startTokenId to initialize _currentIndex with the starting token ID.

The contract developer can customize the starting token ID. For example, a collection might start counting from 1 or 1000. The default in the implementation shown below is 0.

TOKEN COUNTING OPERATIONS

_startTokenId

javascript
function _startTokenId() internal view virtual returns (uint256) {
    return 0;
}

Returns the starting token ID.

_nextTokenId

javascript
function _nextTokenId() internal view virtual returns (uint256) {
    return _currentIndex;
}

Returns _currentIndex, which stores the next token ID to be minted.

totalSupply

javascript
function totalSupply() public view virtual override returns (uint256) {
    unchecked {
        return _currentIndex - _burnCounter - _startTokenId();
    }
}

Returns the number of minted tokens that have not been burned.

It calculates this amount by taking the next token ID, _currentIndex, and subtracting the number of burned tokens, _burnCounter, and the starting token ID returned by _startTokenId.

_totalMinted

javascript
function _totalMinted() internal view virtual returns (uint256) {
    unchecked {
        return _currentIndex - _startTokenId();
    }
}

Returns the total number of tokens minted so far.

Subtracting the starting token ID returned by _startTokenId from _currentIndex gives the cumulative number of minted tokens.

_totalBurned

javascript
function _totalBurned() internal view virtual returns (uint256) {
    return _burnCounter;
}

Returns the total number of burned tokens.

ADDRESS DATA OPERATIONS

balanceOf

javascript
function balanceOf(address owner) public view virtual override returns (uint256) {
    if (owner == address(0)) _revert(BalanceQueryForZeroAddress.selector);
    return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
}

Returns the number of tokens owned by the address supplied as owner.

Condition

  • owner cannot be the zero address.

Bitwise operations extract the balance from the value retrieved from _packedAddressData.

_numberMinted

javascript
function _numberMinted(address owner) internal view returns (uint256) {
    return (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
}

_numberBurned

javascript
function _numberBurned(address owner) internal view returns (uint256) {
    return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
}

Returns the number of tokens burned by the address supplied as owner.

The function uses bit shifts and bitwise operations on the value retrieved from _packedAddressData.

_getAux

javascript
function _getAux(address owner) internal view returns (uint64) {
    return uint64(_packedAddressData[owner] >> _BITPOS_AUX);
}

Returns auxiliary data associated with a token owner.

For example, it can retrieve a value used to track how many tokens an allowlisted address is permitted to mint.

_setAux

javascript
unction _setAux(address owner, uint64 aux) internal virtual {
    uint256 packed = _packedAddressData[owner];
    uint256 auxCasted;
    // Cast `aux` with assembly to avoid redundant masking.
    assembly {
        auxCasted := aux
    }
    packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
    _packedAddressData[owner] = packed;
}

Sets auxiliary data associated with a token owner.

It can store application-specific information, such as the minting allowance of an allowlisted address.

The value is packed into a uint256 using bit shifts and bitwise operations. The missing initial letter in the function declaration in this excerpt is a typo retained from the original code.

IERC165

supportsInterface

javascript
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
    return
        interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
        interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
        interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
}

Checks whether the contract supports ERC165, ERC721, or ERC721Metadata.

It compares the supplied four-byte interfaceId with the corresponding interface identifiers. This is an interface ID, not the first four bits of a contract address.

IERC721Metadata

name

javascript
function name() public view virtual override returns (string memory) {
    return _name;
}

Returns the name of the ERC721 collection.

symbol

javascript
function symbol() public view virtual override returns (string memory) {
    return _symbol;
}

Returns the symbol of the ERC721 collection.

tokenURI

javascript
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
    if (!_exists(tokenId)) _revert(URIQueryForNonexistentToken.selector);

    string memory baseURI = _baseURI();
    return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
}

Returns the tokenURI of an ERC721 token.

Condition

  • tokenId must identify an existing token.

The following article explains tokenURI in more detail.

/articles/0570a8d05bc7c9b9593f

_baseURI

javascript
function _baseURI() internal view virtual returns (string memory) {
    return '';
}

Returns the base URI for the ERC721 collection.

It is empty by default and can be overridden to configure a base URI.

OWNERSHIPS OPERATIONS

ownerOf

javascript
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
    return address(uint160(_packedOwnershipOf(tokenId)));
}

Returns the address of the owner of the token identified by tokenId.

_ownershipOf

javascript
function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
    return _unpackedOwnership(_packedOwnershipOf(tokenId));
}

Returns the ownership data associated with tokenId as a struct.

Ownership struct

  • Owner address
  • Ownership start timestamp
  • Whether the token has been burned
  • Extra data

These four fields are returned together in a struct. The original article refers to the mint timestamp, but the field represents the start of the recorded ownership and may change on transfer.

_ownershipAt

javascript
function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
    return _unpackedOwnership(_packedOwnerships[index]);
}

Uses the supplied index to read an ownership entry and returns the same struct type as _ownershipOf, without resolving an uninitialized entry by searching backward.

_initializeOwnershipAt

javascript
function _initializeOwnershipAt(uint256 index) internal virtual {
    if (_packedOwnerships[index] == 0) {
        _packedOwnerships[index] = _packedOwnershipOf(index);
    }
}

Initializes an ownership entry when the value stored at _packedOwnerships[index] is zero.

Note that the condition is on the stored ownership value, not on whether index itself is zero. Token ID 0 can exist when the collection starts at zero.

_packedOwnershipOf

javascript
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
    if (_startTokenId() <= tokenId) {
        packed = _packedOwnerships[tokenId];
        // If not burned.
        if (packed & _BITMASK_BURNED == 0) {
            if (packed == 0) {
                if (tokenId >= _currentIndex) _revert(OwnerQueryForNonexistentToken.selector);
                for (;;) {
                    unchecked {
                        packed = _packedOwnerships[--tokenId];
                    }
                    if (packed == 0) continue;
                    return packed;
                }
            }
            return packed;
        }
    }
    _revert(OwnerQueryForNonexistentToken.selector);
}

Returns the ownership and associated extra data for tokenId packed into a uint256.

Conditions

  • tokenId must be greater than or equal to the starting token ID and less than the next token ID to be minted (_currentIndex).
  • The token must not have been burned.

_unpackedOwnership

javascript
function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
    ownership.addr = address(uint160(packed));
    ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
    ownership.burned = packed & _BITMASK_BURNED != 0;
    ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
}

Extracts the following four fields into a struct.

Ownership struct

  • Owner address
  • Ownership start timestamp
  • Whether the token has been burned
  • Extra data

_packOwnershipData

javascript
function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
    assembly {
        owner := and(owner, _BITMASK_ADDRESS)
        result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
    }
}

Packs ownership data into a uint256. The resulting word can encode the following fields.

Ownership struct

  • Owner address
  • Ownership start timestamp
  • Whether the token has been burned
  • Extra data

_nextInitializedFlag

javascript
function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
    assembly {
        result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
    }
}

Takes the number of tokens to mint as quantity and returns a packed flag indicating whether that quantity is exactly one rather than multiple tokens.

APPROVAL OPERATIONS

approve

javascript
function approve(address to, uint256 tokenId) public payable virtual override {
    _approve(to, tokenId, true);
}

Grants the address supplied as to permission to transfer the token identified by tokenId.

getApproved

javascript
function getApproved(uint256 tokenId) public view virtual override returns (address) {
    if (!_exists(tokenId)) _revert(ApprovalQueryForNonexistentToken.selector);

    return _tokenApprovals[tokenId].value;
}

Returns the address approved to transfer the token identified by tokenId.

Condition

  • tokenId must identify an existing token.

setApprovalForAll

javascript
function setApprovalForAll(address operator, bool approved) public virtual override {
    _operatorApprovals[_msgSenderERC721A()][operator] = approved;
    emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
}

Allows the caller to grant or revoke the address supplied as operator permission to transfer all tokens owned by the caller.

isApprovedForAll

javascript
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
    return _operatorApprovals[owner][operator];
}

Checks whether the address supplied as operator is approved to transfer all tokens owned by owner.

_exists

javascript
function _exists(uint256 tokenId) internal view virtual returns (bool) {
    return
    _startTokenId() <= tokenId &&
    tokenId < _currentIndex && // If within bounds,
    _packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned.
}

Checks whether the token identified by tokenId has been minted and has not been burned.

_isSenderApprovedOrOwner

javascript
function _isSenderApprovedOrOwner(
    address approvedAddress,
    address owner,
    address msgSender
) private pure returns (bool result) {
    assembly {
        owner := and(owner, _BITMASK_ADDRESS)
        msgSender := and(msgSender, _BITMASK_ADDRESS)
        result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
    }
}

Checks whether the supplied sender is the token owner or an address approved to transfer the token.

_getApprovedSlotAndAddress

javascript
function _getApprovedSlotAndAddress(uint256 tokenId)
    private
    view
    returns (uint256 approvedAddressSlot, address approvedAddress)
{
    TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
    assembly {
        approvedAddressSlot := tokenApproval.slot
        approvedAddress := sload(approvedAddressSlot)
    }
}

Returns the address approved to transfer the token identified by tokenId, together with the storage slot containing that address.

javascript
approvedAddressSlot := tokenApproval.slot
approvedAddress := sload(approvedAddressSlot)

The above section retrieves the storage location and the address stored there.

TRANSFER OPERATIONS

transferFrom

javascript
function transferFrom(
    address from,
    address to,
    uint256 tokenId
) public payable virtual override {
    uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);

    from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));

    if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);

    (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);

    if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
        if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);

    _beforeTokenTransfers(from, to, tokenId, 1);

    assembly {
        if approvedAddress {
            sstore(approvedAddressSlot, 0)
        }
    }
    unchecked {
        --_packedAddressData[from]; // Updates: `balance -= 1`.
        ++_packedAddressData[to]; // Updates: `balance += 1`.

        _packedOwnerships[tokenId] = _packOwnershipData(
            to,
            _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
        );
        if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
            uint256 nextTokenId = tokenId + 1;
            if (_packedOwnerships[nextTokenId] == 0) {
                if (nextTokenId != _currentIndex) {
                    _packedOwnerships[nextTokenId] = prevOwnershipPacked;
                }
            }
        }
    }
    uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
    assembly {
        log4(
            0, // Start of data (0, since no data).
            0, // End of data (0, since no data).
            _TRANSFER_EVENT_SIGNATURE, // Signature.
            from, // `from`.
            toMasked, // `to`.
            tokenId // `tokenId`.
        )
    }
    if (toMasked == 0) _revert(TransferToZeroAddress.selector);

    _afterTokenTransfers(from, to, tokenId, 1);
}

Transfers the token identified by tokenId from from to to.

safeTransferFrom

javascript
function safeTransferFrom(
    address from,
    address to,
    uint256 tokenId
) public payable virtual override {
    safeTransferFrom(from, to, tokenId, '');
}

Calls the overloaded safeTransferFrom function.

safeTransferFrom

javascript
function safeTransferFrom(
    address from,
    address to,
    uint256 tokenId,
    bytes memory _data
) public payable virtual override {
    transferFrom(from, to, tokenId);
    if (to.code.length != 0)
        if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
            _revert(TransferToNonERC721ReceiverImplementer.selector);
        }
}

Calls transferFrom and, when the recipient is a contract, checks that the recipient accepts ERC721 transfers.

Conditions

  • to cannot be the zero address.
  • If the recipient is a contract, it must support the ERC721 receiver callback.

If an ERC721 token is sent to a contract that cannot handle it, the token may become inaccessible.

The safe transfer performs a receiver check so that the transaction reverts if a contract cannot accept the token. This checks the receiver callback rather than requiring the recipient itself to implement the ERC721 token interface.

_beforeTokenTransfers

javascript
function _beforeTokenTransfers(
    address from,
    address to,
    uint256 startTokenId,
    uint256 quantity
) internal virtual {}

A hook called before tokens are transferred.

Override this function to implement additional processing before a transfer.

_afterTokenTransfers

javascript
function _afterTokenTransfers(
    address from,
    address to,
    uint256 startTokenId,
    uint256 quantity
) internal virtual {}

A hook called after tokens are transferred.

Override this function to implement additional processing after a transfer.

_checkContractOnERC721Received

javascript
function _checkContractOnERC721Received(
    address from,
    address to,
    uint256 tokenId,
    bytes memory _data
) private returns (bool) {
    try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
        bytes4 retval
    ) {
        return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
    } catch (bytes memory reason) {
        if (reason.length == 0) {
            _revert(TransferToNonERC721ReceiverImplementer.selector);
        }
        assembly {
            revert(add(32, reason), mload(reason))
        }
    }
}

As discussed in the safeTransferFrom section, this function checks whether a recipient contract accepts ERC721 transfers.

MINT OPERATIONS

_mint

javascript
function _mint(address to, uint256 quantity) internal virtual {
    uint256 startTokenId = _currentIndex;
    if (quantity == 0) _revert(MintZeroQuantity.selector);

    _beforeTokenTransfers(address(0), to, startTokenId, quantity);

    unchecked {
        _packedOwnerships[startTokenId] = _packOwnershipData(
            to,
            _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
        );

        _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);

        uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;

        if (toMasked == 0) _revert(MintToZeroAddress.selector);

        uint256 end = startTokenId + quantity;
        uint256 tokenId = startTokenId;

        do {
            assembly {
                log4(
                    0, // Start of data (0, since no data).
                    0, // End of data (0, since no data).
                    _TRANSFER_EVENT_SIGNATURE, // Signature.
                    0, // `address(0)`.
                    toMasked, // `to`.
                    tokenId // `tokenId`.
                )
            }
        } while (++tokenId != end);

        _currentIndex = end;
    }
    _afterTokenTransfers(address(0), to, startTokenId, quantity);
}

Mints quantity ERC721 tokens to the address supplied as to.

Multiple ERC721 tokens can be minted in a single transaction.

_mintERC2309

javascript
function _mintERC2309(address to, uint256 quantity) internal virtual {
    uint256 startTokenId = _currentIndex;
    if (to == address(0)) _revert(MintToZeroAddress.selector);
    if (quantity == 0) _revert(MintZeroQuantity.selector);
    if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) _revert(MintERC2309QuantityExceedsLimit.selector);

    _beforeTokenTransfers(address(0), to, startTokenId, quantity);

    unchecked {
        _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);

        _packedOwnerships[startTokenId] = _packOwnershipData(
            to,
            _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
        );

        emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);

        _currentIndex = startTokenId + quantity;
    }
    _afterTokenTransfers(address(0), to, startTokenId, quantity);
}

Efficiently mints ERC721 tokens during contract deployment.

It emits the ConsecutiveTransfer event defined by ERC2309 to represent a batch of consecutive ERC721 tokens.

Calling this function outside contract construction would break ERC721 compliance for the implementation discussed here.

See the following proposal for more details.

EIP2309

_safeMint

javascript
function _safeMint(
    address to,
    uint256 quantity,
    bytes memory _data
) internal virtual {
    _mint(to, quantity);

    unchecked {
        if (to.code.length != 0) {
            uint256 end = _currentIndex;
            uint256 index = end - quantity;
            do {
                if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
                    _revert(TransferToNonERC721ReceiverImplementer.selector);
                }
            } while (index < end);
            if (_currentIndex != end) _revert(bytes4(0));
        }
    }
}

Mints multiple ERC721 tokens.

If the recipient is a contract, it also checks whether the recipient accepts ERC721 transfers.

_safeMint

javascript
function _safeMint(address to, uint256 quantity) internal virtual {
    _safeMint(to, quantity, '');
}

Calls the overloaded _safeMint function.

APPROVAL OPERATIONS

_approve

javascript
function _approve(address to, uint256 tokenId) internal virtual {
    _approve(to, tokenId, false);
}

Calls the overloaded _approve function.

_approve

javascript
function _approve(
    address to,
    uint256 tokenId,
    bool approvalCheck
) internal virtual {
    address owner = ownerOf(tokenId);

    if (approvalCheck && _msgSenderERC721A() != owner)
        if (!isApprovedForAll(owner, _msgSenderERC721A())) {
            _revert(ApprovalCallerNotOwnerNorApproved.selector);
        }

    _tokenApprovals[tokenId].value = to;
    emit Approval(owner, to, tokenId);
}

Grants the address supplied as to approval to transfer the token identified by tokenId, subject to the authorization checks requested by the caller.

BURN OPERATIONS

_burn

javascript
function _burn(uint256 tokenId) internal virtual {
    _burn(tokenId, false);
}

Calls the overloaded _burn function.

_burn

javascript
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
    uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);

    address from = address(uint160(prevOwnershipPacked));

    (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);

    if (approvalCheck) {
        if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
            if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
    }

    _beforeTokenTransfers(from, address(0), tokenId, 1);

    assembly {
        if approvedAddress {
            sstore(approvedAddressSlot, 0)
        }
    }
er overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
    unchecked {
        _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;

        _packedOwnerships[tokenId] = _packOwnershipData(
            from,
            (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
        );

        if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
            uint256 nextTokenId = tokenId + 1;
            if (_packedOwnerships[nextTokenId] == 0) {
                if (nextTokenId != _currentIndex) {
                    _packedOwnerships[nextTokenId] = prevOwnershipPacked;
                }
            }
        }
    }

    emit Transfer(from, address(0), tokenId);
    _afterTokenTransfers(from, address(0), tokenId, 1);

    unchecked {
        _burnCounter++;
    }
}

Burns the token identified by tokenId.

EXTRA DATA OPERATIONS

_setExtraDataAt

javascript
function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
    uint256 packed = _packedOwnerships[index];
    if (packed == 0) _revert(OwnershipNotInitializedForExtraData.selector);
    uint256 extraDataCasted;
    assembly {
        extraDataCasted := extraData
    }
    packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
    _packedOwnerships[index] = packed;
}

Sets extra data directly in an ownership entry stored in _packedOwnerships.

_extraData

javascript
function _extraData(
    address from,
    address to,
    uint24 previousExtraData
) internal view virtual returns (uint24) {}

Generates extra data.

The default implementation does not supply custom data. Override this function to include application-specific extra data.

_nextExtraData

javascript
function _nextExtraData(
    address from,
    address to,
    uint256 prevOwnershipPacked
) private view returns (uint256) {
    uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
    return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
}

Calls _extraData to generate the extra data to be packed into an ownership entry in _packedOwnerships.

OTHER OPERATIONS

_msgSenderERC721A

javascript
function _msgSenderERC721A() internal view virtual returns (address) {
    return msg.sender;
}

Returns the address of the message sender.

_toString

javascript
function _toString(uint256 value) internal pure virtual returns (string memory str) {
    assembly {
        let m := add(mload(0x40), 0xa0)
        mstore(0x40, m)
        str := sub(m, 0x20)
        mstore(str, 0)

        let end := str

        for { let temp := value } 1 {} {
            str := sub(str, 1)
            mstore8(str, add(48, mod(temp, 10)))
            temp := div(temp, 10)
            if iszero(temp) { break }
        }

        let length := sub(end, str)
        str := sub(str, 0x20)
        mstore(str, length)
    }
}

Converts the uint256 supplied as value to a string and returns it.

_revert

javascript
function _revert(bytes4 errorSelector) internal pure {
    assembly {
        mstore(0x00, errorSelector)
        revert(0x00, 0x04)
    }
}

A function called to revert with an error.

Implementing ERC721A

ERC721A implementation

Now that we have examined the ERC721A code, let's implement our own example.

This section uses the following documentation as a reference.

Environment setup

Start by setting up the development environment.

Follow the environment setup section of the article below.

Implementing ERC20 deposits and withdrawals from scratch

bash
$ npm i @openzeppelin/contracts

Instead of running the command above, run the following command.

bash
$ npm install --save-dev erc721a

The development environment is now ready.

Creating the contract

Run the following command to create the contract file.

bash
$ touch contracts/ERC721AContract.sol

Paste the following code into the newly created ERC721AContract.sol file.

solidity
pragma solidity ^0.8.4;

import "erc721a/contracts/ERC721A.sol";
import "erc721a/contracts/extensions/ERC721AQueryable.sol";

contract ERC721ANFT is ERC721A, ERC721AQueryable {
    constructor() ERC721A("Azuki", "AZUKI") {}

    function mint(uint256 quantity) external payable {
        // `_mint`'s second argument now takes in a `quantity`, not a `tokenId`.
        _mint(msg.sender, quantity);
    }
}

Let's briefly examine the code.

javascript
import "erc721a/contracts/ERC721A.sol";
import "erc721a/contracts/extensions/ERC721AQueryable.sol";

The contract uses ERC721A.sol and ERC721AQueryable.sol.

These files can be imported from the erc721a package installed during environment setup.

ERC721AQueryable.sol provides functions for retrieving the list of ERC721 tokens owned by an address.

plain
constructor() ERC721A("Azuki", "AZUKI") {}

function mint(uint256 quantity) external payable {
    // `_mint`'s second argument now takes in a `quantity`, not a `tokenId`.
    _mint(msg.sender, quantity);
}

At deployment, the constructor passes Azuki as the collection name and AZUKI as the symbol.

The mint function is used to mint new tokens.

Pass the number of tokens you want to mint in a single operation as quantity, and the function mints that number of tokens.

This completes the contract.

Creating the test file

Create a test file using the path shown below.

bash
$ mkdir test/test-ERC721.js

The original command uses mkdir, which creates a directory rather than a file. Use touch test/test-ERC721.js to create the file instead.

Paste the following code into test-ERC721.js.

javascript
const { expect } = require("chai");

describe("ERC721A", function () {
  beforeEach(async function () {
    [owner, wallet1, wallet2] = await ethers.getSigners();

    // ERC721Aコントラクトを取得。
    ERC721A = await ethers.getContractFactory("ERC721ANFT", owner);

    // ERC721Aコントラクトをデプロイ。
    erc721A = await ERC721A.deploy();

    // トークンをmintする。
    await erc721A.connect(wallet1).mint(10);
    await erc721A.connect(wallet2).mint(20);
    await erc721A.connect(wallet1).mint(5);
    expect(await erc721A.totalSupply()).to.equal(35);
  });

  describe("Check ERC721A Token", function () {
    // トークンの総供給量を確認
    it("Total Supply", async function () {
      expect(await erc721A.totalSupply()).to.equal(35);
    });
    // Wallet1が所有しているトークンの総量を確認
    it("Wallet1 BalanceOf", async function () {
      expect(await erc721A.balanceOf(wallet1.address)).to.equal(15);
    });
    // Wallet2が所有しているトークンの総量を確認
    it("Wallet2 BalanceOf", async function () {
      expect(await erc721A.balanceOf(wallet2.address)).to.equal(20);
    });
    // トークン1の所有者を確認
    it("Token1 ownerOf", async function () {
      expect(await erc721A.ownerOf(1)).to.equal(wallet1.address);
    });
    // トークン15の所有者を確認
    it("Token1 ownerOf", async function () {
      expect(await erc721A.ownerOf(15)).to.equal(wallet2.address);
    });
      ;
  });
  describe("Check ERC721A Token List", function () {
    // wallet1が所有しているトークンの量を確認
      it("wallet1 tokensOfOwner", async function () {
          const wallet1Token = await erc721A.tokensOfOwner(wallet1.address);
        expect(wallet1Token.length).to.equal(15);
    });
    // wallet2が所有しているトークンの量を確認
      it("wallet1 tokensOfOwner", async function () {
          const wallet2Token = await erc721A.tokensOfOwner(wallet2.address);
        expect(wallet2Token.length).to.equal(20);
    });
      ;
  });
});

The test performs the following operations.

Test operations

  • Mint tokens from wallet1 and wallet2.
  • Check the number of tokens owned by wallet1 and wallet2.
  • Retrieve the token IDs owned by each wallet and verify the number returned.

The code comments explain the individual operations in more detail.

Running the tests

With the test file ready, remove the unnecessary sample test file as shown below.

bash
$ rm test/Lock.js

Run the tests using the following command.

bash
$ npx hardhat test

The following output, recorded in the original article, illustrates a successful test run.

bash
  ERC721A
    Check ERC721A Token
      ✔ Total Supply
      ✔ Wallet1 BalanceOf
      ✔ Wallet2 BalanceOf
      ✔ Token1 ownerOf
      ✔ Token1 ownerOf
    Check ERC721A Token List
      ✔ wallet1 tokensOfOwner (41ms)
      ✔ wallet1 tokensOfOwner (39ms)

  7 passing (2s)

Source code

The source code is available in the following repository.

GitHub - ERC721/ERC721A

Conclusion

Conclusion

This article covered the features, internal structure, and implementation of ERC721A.

Although some aspects of the implementation can be challenging, I hope the explanation helps you understand ERC721A and serves as a reference when building your own contracts.

References

https://media.leadedge-c.com/articles/what-is-erc

https://www.erc721a.org/

ERC721A documentation

What does Azuki's NFT implementation ERC721A do?