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 the ERC721 extensions one by one, using OpenZeppelin's implementations as the basis for the discussion.

OpenZeppelin ERC721

There are seven ERC721 extensions covered here.

Extensions

  • ERC721Pausable
  • ERC721Burnable
  • ERC721Consecutive
  • ERC721URIStorage
  • ERC721Votes
  • ERC721Royalty
  • ERC721Wrapper

This is a fairly long article, so use it as a reference when you need to check how a particular extension is implemented.

I also presented a condensed version of this material at the following study group.

CryptoGames Web3 study group

The examples use OpenZeppelin Contracts v4.9.2. The original figures are retained; some figure labels remain in Japanese. Where the historical explanation differs from the accompanying code, translation notes identify the discrepancy.

What is ERC721?

What is ERC721?

If you are unfamiliar with ERC721 itself, refer to the following article.

/articles/0570a8d05bc7c9b9593f

ERC721Pausable

ERC721Pausable

An extension for pausing contract functionality.

This ERC721 extension allows operations such as minting new NFTs and transferring them to other addresses to be enabled or disabled.

The implementation code is shown below.

Pausable.sol

solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../utils/Context.sol";

abstract contract Pausable is Context {
    event Paused(address account);

    event Unpaused(address account);

    bool private _paused;

    constructor() {
        _paused = false;
    }

    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    modifier whenPaused() {
        _requirePaused();
        _;
    }

    function paused() public view virtual returns (bool) {
        return _paused;
    }

    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

contracts/security/Pausable.sol

Paused (Event)

A log emitted when NFT minting or transfer functionality in the ERC721 contract is paused.

Unpaused (Event)

A log emitted when the pause on NFT minting or transfer functionality in the ERC721 contract is lifted.

whenNotPaused (modifier)

A modifier that checks whether NFT minting and transfer functionality in the ERC721 contract is not paused.

Execution proceeds only when the contract is not paused.

A modifier is an optional feature attached to a function that can perform specific checks before function execution.

whenPaused

A modifier that checks whether NFT minting and transfer functionality in the ERC721 contract is paused.

Execution proceeds only when the contract is paused.

paused

A function that checks whether the ERC721 contract is currently paused.

_requireNotPaused

A function that reverts if the ERC721 contract is paused.

_requirePaused

A function that reverts if the ERC721 contract is not paused.

_pause

A function that pauses the ERC721 contract.

It cannot execute successfully if the contract is already paused.

_unpause

A function that unpauses the ERC721 contract.

It cannot execute successfully if the contract is not paused.

ERC721Pausable.sol

solidity
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.2) (token/ERC721/extensions/ERC721Pausable.sol)

pragma solidity ^0.8.0;

import "../ERC721.sol";
import "../../../security/Pausable.sol";

abstract contract ERC721Pausable is ERC721, Pausable {
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual override {
        super._beforeTokenTransfer(from, to, firstTokenId, batchSize);

        require(!paused(), "ERC721Pausable: token transfer while paused");
    }
}

contracts/token/ERC721/extensions/ERC721Pausable.sol

_beforeTokenTransfer

This function is called before operations such as minting and transferring NFTs in the ERC721 contract.

It is useful for performing checks before an operation proceeds.

It imports and uses the Pausable.sol contract discussed above.

ERC721Burnable

ERC721Burnable

An extension for burning a specific NFT.

This extension exposes a function for burning an already minted ERC721 NFT.

Although burning is exposed as an extension, OpenZeppelin implements the underlying operation in ERC721.sol.

contracts/token/ERC721/ERC721.sol

ERC721Burnable.sol

solidity
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Burnable.sol)

pragma solidity ^0.8.0;

import "../ERC721.sol";
import "../../../utils/Context.sol";

abstract contract ERC721Burnable is Context, ERC721 {
    function burn(uint256 tokenId) public virtual {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _burn(tokenId);
    }
}

contracts/token/ERC721/extensions/ERC721Burnable.sol

burn

Checks whether the caller is the owner of the ERC721 NFT or an address approved by the owner.

If the check returns true, it calls the _burn function in ERC721.sol.

ERC721.sol

javascript
...
function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId, 1);

        owner = ERC721.ownerOf(tokenId);

        delete _tokenApprovals[tokenId];

        unchecked {
            _balances[owner] -= 1;
        }
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId, 1);
    }
...

contracts/token/ERC721/ERC721.sol

_burn

Retrieves the owner's address using the token ID of the ERC721 NFT to burn.

A token ID is a unique value that identifies an NFT. Numbers such as 1 and 2 are commonly used.

It then calls _beforeTokenTransfer and executes any logic defined in that hook.

Because the owner may have changed as a result of that logic, the function retrieves the address of the NFT's owner again.

It clears the approval granted to an address authorized to operate the NFT.

It reduces the owner's NFT balance by 1 and deletes the ownership record.

Finally, it emits the Transfer event and calls _afterTokenTransfer, executing any logic defined there.

ERC721Consecutive

ERC721Consecutive

An extension for minting multiple ERC721 NFTs at once.

This extension makes it possible to mint multiple ERC721 NFTs in a single batch, but only during contract deployment.

It is based on the proposal in ERC2309.

Refer to the following article for more information about ERC2309.

[ERC2309] Understanding the standard event for creating or transferring multiple NFTs

One important restriction is that individual ERC721 NFTs cannot be minted while this batch minting mechanism is in use during construction.

ERC721Consecutive's batch minting operation is available only during contract deployment.

Other minting operations are prevented in order to maintain consecutive token IDs.

ERC721Consecutive.sol

solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../ERC721.sol";
import "../../../interfaces/IERC2309.sol";
import "../../../utils/Checkpoints.sol";
import "../../../utils/structs/BitMaps.sol";

abstract contract ERC721Consecutive is IERC2309, ERC721 {
    using BitMaps for BitMaps.BitMap;
    using Checkpoints for Checkpoints.Trace160;

    Checkpoints.Trace160 private _sequentialOwnership;
    BitMaps.BitMap private _sequentialBurn;

    function _maxBatchSize() internal view virtual returns (uint96) {
        return 5000;
    }

    function _ownerOf(uint256 tokenId) internal view virtual override returns (address) {
        address owner = super._ownerOf(tokenId);

        if (owner != address(0) || tokenId > type(uint96).max) {
            return owner;
        }

        return _sequentialBurn.get(tokenId) ? address(0) : address(_sequentialOwnership.lowerLookup(uint96(tokenId)));
    }

    function _mintConsecutive(address to, uint96 batchSize) internal virtual returns (uint96) {
        uint96 first = _totalConsecutiveSupply();

        if (batchSize > 0) {
            require(!Address.isContract(address(this)), "ERC721Consecutive: batch minting restricted to constructor");
            require(to != address(0), "ERC721Consecutive: mint to the zero address");
            require(batchSize <= _maxBatchSize(), "ERC721Consecutive: batch too large");

            _beforeTokenTransfer(address(0), to, first, batchSize);

            uint96 last = first + batchSize - 1;
            _sequentialOwnership.push(last, uint160(to));

            __unsafe_increaseBalance(to, batchSize);

            emit ConsecutiveTransfer(first, last, address(0), to);

            _afterTokenTransfer(address(0), to, first, batchSize);
        }

        return first;
    }

    function _mint(address to, uint256 tokenId) internal virtual override {
        require(Address.isContract(address(this)), "ERC721Consecutive: can't mint during construction");
        super._mint(to, tokenId);
    }

    function _afterTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual override {
        if (
            to == address(0) && // if we burn
            firstTokenId < _totalConsecutiveSupply() && // and the tokenId was minted in a batch
            !_sequentialBurn.get(firstTokenId) // and the token was never marked as burnt
        ) {
            require(batchSize == 1, "ERC721Consecutive: batch burn not supported");
            _sequentialBurn.set(firstTokenId);
        }
        super._afterTokenTransfer(from, to, firstTokenId, batchSize);
    }

    function _totalConsecutiveSupply() private view returns (uint96) {
        (bool exists, uint96 latestId, ) = _sequentialOwnership.latestCheckpoint();
        return exists ? latestId + 1 : 0;
    }
}

contracts/token/ERC721/extensions/ERC721Consecutive.sol

_maxBatchSize

Returns the maximum number of ERC721 NFTs that can be minted at once.

Without a maximum, an excessively large number of NFTs could be minted.

This could cause problems such as addresses being unable to receive NFTs that they should have received or transactions failing.

_ownerOf

Returns the owner of a particular ERC721 NFT.

The original explanation describes the function as returning the owner when the owner is the zero address or when the specified tokenId is within the range of uint96.

As discussed in the _mintConsecutive section, when multiple NFTs are minted at once, the contract stores a checkpoint representing the batch rather than an individual ownership record for each NFT. Consequently, a direct ownership lookup may return the zero address, requiring a separate lookup.

The reason for checking the range of uint96 rather than uint256 is that a uint256 value is larger, whereas using a smaller integer helps minimize storage and gas costs.

For tokens that require the batch ownership lookup, the function checks whether the specified NFT has been burned before returning its owner.

Translation note: The code above actually returns the ordinary ownership result when owner != address(0) or tokenId > type(uint96).max. Otherwise it checks the burn bitmap and looks up the batch's ownership checkpoint. This is the reverse of the original prose's stated first condition.

_mintConsecutive

Mints multiple ERC721 NFTs.

The following conditions apply to this function.

Conditions

  • Check that the batchSize argument does not exceed _maxBatchSize, the maximum number of NFTs that can be minted at once.
  • Execute the batch mint from the constructor, which runs during contract deployment.
  • Because it executes in the constructor, it does not emit individual Transfer events.
  • It does not call onERC721Received to check whether the destination is a contract.
  • It emits the ConsecutiveTransfer event defined in ERC2309.

The function performs the following operations under these conditions.

It calls _totalConsecutiveSupply(), retrieves the number of NFTs minted consecutively so far, and stores the result in a variable called first.

If the batchSize argument is 0, it returns only the value of first and finishes.

If batchSize is at least 1, it performs the following three checks.

Checks

  • Is execution taking place in the constructor?
  • Is the mint destination a nonzero address?
  • Is batchSize less than or equal to _maxBatchSize?

It calls _beforeTokenTransfer and executes any logic defined in the hook.

It records ownership of the NFTs in the specified range in the _sequentialOwnership structure. The original explanation describes storing the last tokenId + 1; the implementation above instead stores the last token ID itself (first + batchSize - 1) together with the owner.

The following is an example of a struct.

javascript
struct User {
    string name;
    address owner;
    uint256 id;  
}

It executes __unsafe_increaseBalance to increase the number of NFTs held by the owner of the newly minted NFTs.

It emits ConsecutiveTransfer, recording the event in the log.

Finally, it calls _afterTokenTransfer, executes any defined logic, and returns first, the first token ID of the newly minted batch.

_mint

Mints an individual ERC721 NFT.

During deployment, _mintConsecutive is the supported minting operation, and _mint cannot be used.

After deployment, _mintConsecutive can no longer mint a nonzero batch, while _mint becomes available.

_afterTokenTransfer

A function called after an ERC721 NFT is minted or transferred.

The function records the burn of an NFT identified by its token ID when the following conditions hold.

Conditions

  • The to address is the zero address.
  • firstTokenId is smaller than the total consecutive supply and identifies an NFT minted in a batch.
  • The NFT identified by firstTokenId has not already been marked as burned.
  • batchSize is 1.

When these conditions are met, the function marks the token as burned in _sequentialBurn.

Finally, it calls super._afterTokenTransfer to execute the parent class's hook.

_totalConsecutiveSupply

The original explanation describes this as returning the ERC721 NFTs minted plus 1. More precisely, the code returns the latest consecutive token ID plus 1, or 0 when no checkpoint exists.

It calls _sequentialOwnership.latestCheckpoint() to retrieve the latest data in the _sequentialOwnership structure.

The call returns information about whether the data exists (exists) and the latest token ID (latestId).

If exists is true, the function adds 1 to latestId and returns the resulting consecutive supply.

If exists is false, it returns 0.

ERC721URIStorage

ERC721URIStorage

An extension for storing URI data in the contract.

This extension allows tokenURI data to be stored within the contract.

A token URI typically holds a URL, expressed as a string beginning with something such as https://, for accessing information associated with an NFT, including its metadata. ERC721 metadata commonly contains information such as the NFT's name, description, and image link. The original explanation also mentions the owner's address, which is not required by the standard metadata schema.

ERC721URIStorage

solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../ERC721.sol";
import "../../../interfaces/IERC4906.sol";

abstract contract ERC721URIStorage is IERC4906, ERC721 {
    using Strings for uint256;

    mapping(uint256 => string) private _tokenURIs;

    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) {
        return interfaceId == bytes4(0x49064906) || super.supportsInterface(interfaceId);
    }

    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireMinted(tokenId);

        string memory _tokenURI = _tokenURIs[tokenId];
        string memory base = _baseURI();

        if (bytes(base).length == 0) {
            return _tokenURI;
        }
        if (bytes(_tokenURI).length > 0) {
            return string(abi.encodePacked(base, _tokenURI));
        }
        return super.tokenURI(tokenId);
    }

    function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
        require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
        _tokenURIs[tokenId] = _tokenURI;

        emit MetadataUpdate(tokenId);
    }

    function _burn(uint256 tokenId) internal virtual override {
        super._burn(tokenId);

        if (bytes(_tokenURIs[tokenId]).length != 0) {
            delete _tokenURIs[tokenId];
        }
    }
}

contracts/token/ERC721/extensions/ERC721URIStorage.sol

_tokenURIs

A mapping associating each ERC721 NFT with its URI.

supportsInterface

Checks whether a contract supports ERC4906.

It checks whether the interfaceId argument equals 0x49064906.

If the values match, it returns true to indicate ERC4906 support. Otherwise, it calls the inherited supportsInterface implementation.

tokenURI

Retrieves the token URI of a particular ERC721 NFT.

It calls _requireMinted to check whether the tokenId supplied as an argument exists.

If the token exists, the function retrieves the token URI for tokenId and calls _baseURI to retrieve the base URI.

If no base URI is configured, it returns the token URI to the caller.

When both a base URI and a token URI are present, it returns their concatenation.

If the token-specific URI is absent but a base URI exists, it calls the inherited super.tokenURI function. The original explanation describes the fallback as occurring when both URIs are absent; the preceding empty-base check in the code actually takes precedence.

_setTokenURI

Sets or updates the token URI of a particular ERC721 NFT.

It checks whether the tokenId supplied as an argument exists.

If it exists, the supplied _tokenURI is set or updated as the metadata reference for that NFT.

_burn

Burns a particular ERC721 NFT.

Using the supplied tokenId, it calls the parent class's _burn function to burn the NFT.

It then checks whether the burned NFT has an associated token URI.

If the length of _tokenURIs[tokenId] is not 0, the token URI has been set.

When the URI exists, it deletes it from the _tokenURIs mapping.

This ensures that when a particular NFT is burned, its associated token URI is removed as well.

ERC721Votes

ERC721Votes

An extension that allows the voting unit associated with an NFT to be delegated to the holder or another address.

Each NFT represents one voting unit, which can be delegated to the holder's own address or to another address.

Delegation can be understood as assigning voting power to an address and activating it.

Because maintaining delegation incurs additional cost, voting units are not counted as active votes until delegated.

Activation means making voting power available. Inactive voting power cannot be used to vote.

The extension provides a mechanism for delegating voting power based on ERC721 NFTs and tracking each address's delegation history, allowing NFT holders to participate in governance decisions.

Voting events and voting itself are implemented in a separate contract.

Votes.sol

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "../../interfaces/IERC5805.sol";
import "../../utils/Context.sol";
import "../../utils/Counters.sol";
import "../../utils/Checkpoints.sol";
import "../../utils/cryptography/EIP712.sol";

abstract contract Votes is Context, EIP712, IERC5805 {
    using Checkpoints for Checkpoints.Trace224;
    using Counters for Counters.Counter;

    bytes32 private constant _DELEGATION_TYPEHASH =
        keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");

    mapping(address => address) private _delegation;

    mapping(address => Checkpoints.Trace224) private _delegateCheckpoints;

    Checkpoints.Trace224 private _totalCheckpoints;

    mapping(address => Counters.Counter) private _nonces;

    function clock() public view virtual override returns (uint48) {
        return SafeCast.toUint48(block.number);
    }

    function CLOCK_MODE() public view virtual override returns (string memory) {
        require(clock() == block.number, "Votes: broken clock mode");
        return "mode=blocknumber&from=default";
    }

    function getVotes(address account) public view virtual override returns (uint256) {
        return _delegateCheckpoints[account].latest();
    }

    function getPastVotes(address account, uint256 timepoint) public view virtual override returns (uint256) {
        require(timepoint < clock(), "Votes: future lookup");
        return _delegateCheckpoints[account].upperLookupRecent(SafeCast.toUint32(timepoint));
    }

    function getPastTotalSupply(uint256 timepoint) public view virtual override returns (uint256) {
        require(timepoint < clock(), "Votes: future lookup");
        return _totalCheckpoints.upperLookupRecent(SafeCast.toUint32(timepoint));
    }

    function _getTotalSupply() internal view virtual returns (uint256) {
        return _totalCheckpoints.latest();
    }

    function delegates(address account) public view virtual override returns (address) {
        return _delegation[account];
    }

    function delegate(address delegatee) public virtual override {
        address account = _msgSender();
        _delegate(account, delegatee);
    }

    function delegateBySig(
        address delegatee,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        require(block.timestamp <= expiry, "Votes: signature expired");
        address signer = ECDSA.recover(
            _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
            v,
            r,
            s
        );
        require(nonce == _useNonce(signer), "Votes: invalid nonce");
        _delegate(signer, delegatee);
    }

    function _delegate(address account, address delegatee) internal virtual {
        address oldDelegate = delegates(account);
        _delegation[account] = delegatee;

        emit DelegateChanged(account, oldDelegate, delegatee);
        _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));
    }

    function _transferVotingUnits(address from, address to, uint256 amount) internal virtual {
        if (from == address(0)) {
            _push(_totalCheckpoints, _add, SafeCast.toUint224(amount));
        }
        if (to == address(0)) {
            _push(_totalCheckpoints, _subtract, SafeCast.toUint224(amount));
        }
        _moveDelegateVotes(delegates(from), delegates(to), amount);
    }

    function _moveDelegateVotes(address from, address to, uint256 amount) private {
        if (from != to && amount > 0) {
            if (from != address(0)) {
                (uint256 oldValue, uint256 newValue) = _push(
                    _delegateCheckpoints[from],
                    _subtract,
                    SafeCast.toUint224(amount)
                );
                emit DelegateVotesChanged(from, oldValue, newValue);
            }
            if (to != address(0)) {
                (uint256 oldValue, uint256 newValue) = _push(
                    _delegateCheckpoints[to],
                    _add,
                    SafeCast.toUint224(amount)
                );
                emit DelegateVotesChanged(to, oldValue, newValue);
            }
        }
    }

    function _push(
        Checkpoints.Trace224 storage store,
        function(uint224, uint224) view returns (uint224) op,
        uint224 delta
    ) private returns (uint224, uint224) {
        return store.push(SafeCast.toUint32(clock()), op(store.latest(), delta));
    }

    function _add(uint224 a, uint224 b) private pure returns (uint224) {
        return a + b;
    }

    function _subtract(uint224 a, uint224 b) private pure returns (uint224) {
        return a - b;
    }

    function _useNonce(address owner) internal virtual returns (uint256 current) {
        Counters.Counter storage nonce = _nonces[owner];
        current = nonce.current();
        nonce.increment();
    }

    function nonces(address owner) public view virtual returns (uint256) {
        return _nonces[owner].current();
    }

    function DOMAIN_SEPARATOR() external view returns (bytes32) {
        return _domainSeparatorV4();
    }

    function _getVotingUnits(address) internal view virtual returns (uint256);
}

contracts/governance/utils/Votes.sol

_delegation

Stores the delegatee for each address.

_delegateCheckpoints

Stores the history of delegated voting power for each account.

_totalCheckpoints

Stores historical checkpoints for the total supply of voting units.

_nonces

Stores a unique identifier called a nonce for each address.

clock

Returns a reference point in time.

By default, it uses the block number, converts it to a 48-bit integer, and returns it.

A reference point can be used to determine how many NFTs their respective holders owned at that point in time.

CLOCK_MODE

Provides the caller with information about the mode of the clock function.

It calls clock to verify that the clock behaves as expected.

If the clock is operating normally, it returns the string mode=blocknumber&from=default.

getVotes

Returns the current voting power of a particular address.

getPastVotes

Returns the voting power of a particular address at a point in the past.

getPastTotalSupply

Returns the historical total supply of voting units.

Translation note: The original calls this the total number of votes not yet cast. The code returns total voting units, regardless of whether they are delegated or have been used to vote.

_getTotalSupply

Returns the current total supply of voting units. As with getPastTotalSupply, this is not a count of votes that have not yet been cast.

delegates

Returns the address to which a particular account delegates its voting power. The original describes a list of addresses, whereas the function returns a single address.

delegate

Delegates voting power to an address.

It retrieves the address executing the function.

delegateBySig

Verifies signature information when delegating voting power.

The following conditions and operations are checked.

Conditions

  • Has the signature expired?
  • Recover the signer's address using the signed data hash and the values v, r, and s.
  • Has the signing address's nonce already been used?

Once these checks pass, the delegation is performed.

_delegate

Delegates all voting units associated with a particular address.

It retrieves the voting units currently held by the address.

It then delegates all those units to the address specified by the delegatee argument.

_transferVotingUnits

Transfers voting units.

When from is the zero address, the function adds amount voting units to _totalCheckpoints using _add.

This increases total voting units.

When to is the zero address, it removes amount voting units from _totalCheckpoints using _subtract.

This decreases total voting units.

It calls _moveDelegateVotes to move amount voting units between the delegatees of the addresses specified by from and to.

The function therefore manages both changes in total voting units and transfers of voting power.

_moveDelegateVotes

Moves delegated voting power.

First, it checks that from and to are different addresses and that amount is greater than 0.

If from is not the zero address, it uses _subtract to subtract amount voting units from _delegateCheckpoints[from], the source address's checkpoints.

If to is not the zero address, it uses _add to add amount voting units to _delegateCheckpoints[to], the destination address's checkpoints.

It emits DelegateVotesChanged to record the movement of delegated voting power in the log.

_push

Creates a new checkpoint and stores the history of increases and decreases in an address's voting power.

_add

Adds two values and returns the result.

_subtract

Subtracts one value from another and returns the result.

_useNonce

Returns the nonce value of the address specified by owner and increments it by 1.

nonces

Returns the nonce value of the address specified by owner.

_getVotingUnits

Returns the number of voting units held by an address.

A contract that uses this contract must implement this function.

ERC721Votes

solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../ERC721.sol";
import "../../../governance/utils/Votes.sol";

abstract contract ERC721Votes is ERC721, Votes {
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual override {
        _transferVotingUnits(from, to, batchSize);
        super._afterTokenTransfer(from, to, firstTokenId, batchSize);
    }

    function _getVotingUnits(address account) internal view virtual override returns (uint256) {
        return balanceOf(account);
    }
}

contracts/token/ERC721/extensions/ERC721Votes.sol

_afterTokenTransfer

Adjusts voting power when an NFT is transferred.

It executes _transferVotingUnits to move voting units associated with the transfer of ERC721 NFTs.

It also calls super._afterTokenTransfer to execute the parent class's hook.

_getVotingUnits

Returns the number of voting units associated with a particular address.

It returns the voting units (number of ERC721 NFTs) held by the address specified by the account argument.

ERC721Royalty

ERC721Royalty

An extension for defining royalties when an NFT is sold.

The original describes this as enforcing royalties. ERC2981 actually exposes royalty payment information; it does not itself enforce payment by marketplaces.

A royalty is a portion of the proceeds from a secondary sale that goes to the creator.

https://qiita.com/cardene/items/456ccacca080fd72e3ec#%E5%AE%9F%E8%A3%85%E4%BE%8Berc721

The following article also covers ERC721Royalty.

Understanding ERC2981 and NFT royalty enforcement

ERC2981.sol

solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../../interfaces/IERC2981.sol";
import "../../utils/introspection/ERC165.sol";

abstract contract ERC2981 is IERC2981, ERC165 {
    struct RoyaltyInfo {
        address receiver;
        uint96 royaltyFraction;
    }

    RoyaltyInfo private _defaultRoyaltyInfo;
    mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;

    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
        return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
    }

    function royaltyInfo(uint256 tokenId, uint256 salePrice) public view virtual override returns (address, uint256) {
        RoyaltyInfo memory royalty = _tokenRoyaltyInfo[tokenId];

        if (royalty.receiver == address(0)) {
            royalty = _defaultRoyaltyInfo;
        }
        uint256 royaltyAmount = (salePrice * royalty.royaltyFraction) / _feeDenominator();
        return (royalty.receiver, royaltyAmount);
    }

    function _feeDenominator() internal pure virtual returns (uint96) {
        return 10000;
    }

    function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
        require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
        require(receiver != address(0), "ERC2981: invalid receiver");

        _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
    }

    function _deleteDefaultRoyalty() internal virtual {
        delete _defaultRoyaltyInfo;
    }

    function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) internal virtual {
        require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
        require(receiver != address(0), "ERC2981: Invalid parameters");

        _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
    }

    function _resetTokenRoyalty(uint256 tokenId) internal virtual {
        delete _tokenRoyaltyInfo[tokenId];
    }
}

contracts/token/common/ERC2981.sol

RoyaltyInfo

A struct representing royalty information.

RoyaltyInfo

  • receiver
    • Address that receives the royalty.
  • royaltyFraction
    • Royalty fraction relative to the sale price.

_defaultRoyaltyInfo

The default royalty.

It applies to NFTs that do not have individually configured royalty information.

_tokenRoyaltyInfo

Stores royalty information for each NFT.

supportsInterface

Checks whether the IERC2981 interface is supported.

royaltyInfo

Calculates the royalty recipient address and royalty amount for the NFT identified by tokenId.

It retrieves the token's royalty information from _tokenRoyaltyInfo.

If no royalty information has been set for that token, it uses _defaultRoyaltyInfo.

It computes the royalty amount using the sale price and the royalty fraction (royalty.royaltyFraction) and returns the result.

_feeDenominator

Returns the denominator used to interpret the fraction when calculating royalty fees.

The royalty is calculated using the following formula.

Sale price × royalty fraction / _feeDenominator

The original explanation refers to a per-mille (‰) denominator, where a percentage is multiplied by 10, with examples of 10% corresponding to 100‰ and 25% corresponding to 250‰. It explains that using integer fractions helps avoid the rounding problems that may arise when using percentages.

Translation note: The accompanying OpenZeppelin implementation actually returns 10000 from _feeDenominator, so its default convention is basis points, not per mille. Under that convention, 10% corresponds to 1000 and 25% to 2500.

_setDefaultRoyalty

Configures the default royalty.

The function performs the following checks.

Conditions

  • feeNumerator is not greater than _feeDenominator.
  • receiver is not the zero address.

_deleteDefaultRoyalty

Deletes the default royalty.

_setTokenRoyalty

Sets a royalty for a particular NFT.

It configures the royalty for the NFT identified by tokenId when the following conditions are met.

Conditions

  • feeNumerator is not greater than _feeDenominator.
  • receiver is not the zero address.

_resetTokenRoyalty

Removes the royalty configuration for a particular NFT.

ERC721Wrapper

ERC721Wrapper

An extension for minting tokens that wrap ERC721 NFTs.

Converting an ERC721 NFT into another token while retaining the original NFT is called wrapping.

Wrapping NFTs can make it possible to combine tokens with other digital assets for governance or voting, or to give them additional interoperability with other tokens.

Because the wrapped token is associated with the original token, the wrapped token can be burned when necessary to recover the original token.

Wrapping is thus a way to convert tokens into another form and provide new functions or uses.

The following are illustrative use cases for wrapping in general; the examples involving rental rights or multiple tokens would require additional application logic beyond the one-to-one ERC721Wrapper implementation.

Use cases

  • Wrap an NFT from game A (a card game) to create an NFT that can be used in game B (an RPG).
  • Wrap an NFT to create a usage-rights NFT that allows the NFT to be rented.
  • Wrap an NFT to create multiple NFTs.
    • For example, wrap the NFT with token ID 1 to create NFTs with token IDs 1001, 1002, and 1003.

ERC721Wrapper

solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../ERC721.sol";

abstract contract ERC721Wrapper is ERC721, IERC721Receiver {
    IERC721 private immutable _underlying;

    constructor(IERC721 underlyingToken) {
        _underlying = underlyingToken;
    }

    function depositFor(address account, uint256[] memory tokenIds) public virtual returns (bool) {
        uint256 length = tokenIds.length;
        for (uint256 i = 0; i < length; ++i) {
            uint256 tokenId = tokenIds[i];

            underlying().transferFrom(_msgSender(), address(this), tokenId);
            _safeMint(account, tokenId);
        }

        return true;
    }

    function withdrawTo(address account, uint256[] memory tokenIds) public virtual returns (bool) {
        uint256 length = tokenIds.length;
        for (uint256 i = 0; i < length; ++i) {
            uint256 tokenId = tokenIds[i];
            require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Wrapper: caller is not token owner or approved");
            _burn(tokenId);
            underlying().safeTransferFrom(address(this), account, tokenId);
        }

        return true;
    }

    function onERC721Received(
        address,
        address from,
        uint256 tokenId,
        bytes memory
    ) public virtual override returns (bytes4) {
        require(address(underlying()) == _msgSender(), "ERC721Wrapper: caller is not underlying");
        _safeMint(from, tokenId);
        return IERC721Receiver.onERC721Received.selector;
    }

    function _recover(address account, uint256 tokenId) internal virtual returns (uint256) {
        require(underlying().ownerOf(tokenId) == address(this), "ERC721Wrapper: wrapper is not token owner");
        _safeMint(account, tokenId);
        return tokenId;
    }

    function underlying() public view virtual returns (IERC721) {
        return _underlying;
    }
}

contracts/token/ERC721/extensions/ERC721Wrapper.sol

_underlying

A private, immutable value holding the underlying ERC721 contract whose NFTs are wrapped.

depositFor

Deposits ERC721 NFTs and mints their corresponding wrapped tokens.

The function performs the following operations for every element of the tokenIds array.

Operations

  • Transfer the NFT from the owner's address to the wrapper contract's address.
  • Execute _safeMint to mint a token corresponding to the deposited NFT's token ID to the address specified by account.

Once all operations complete, it returns true to the caller.

withdrawTo

Burns wrapped tokens and recovers the corresponding NFTs.

The function performs the following operations for every element of the tokenIds array.

Operations

  • Execute _isApprovedOrOwner to check whether the caller owns the NFT with the specified token ID or is authorized by its owner.
  • Execute _burn to burn the wrapped token.
  • Call underlying and transfer the original NFT corresponding to the burned token from the wrapper contract to the address specified by account.

Once all operations complete, it returns true to the caller.

onERC721Received

Mints a wrapped token when an ERC721 NFT is sent to the contract.

It calls underlying to check whether the address of the contract issuing the ERC721 NFTs matches the calling address.

If the addresses do not match, it reverts.

It executes _safeMint to mint the token with the specified token ID.

This creates the wrapped token and assigns it to the original NFT owner's address.

It returns IERC721Receiver.onERC721Received.selector to inform the sending contract that receipt completed successfully.

_recover

Mints a wrapped token with the corresponding token ID when an underlying ERC721 NFT has been sent to this contract by mistake.

It uses underlying().ownerOf(tokenId) to verify that the owner of the specified tokenId is this contract.

If the owner is not this contract, it reverts.

It executes _safeMint to mint a wrapped token with the same token ID to the address specified by account.

This makes it possible to create the corresponding wrapped token even when the underlying NFT was transferred incorrectly.

It returns tokenId to the caller.

underlying

Returns the underlying ERC721 NFT contract whose tokens are wrapped.

Conclusion

Conclusion

This article introduced the seven ERC721 extensions one by one. The discussion was rather long because there were seven of them to cover.

Takeaways

  • Understand the basic purpose of ERC721 extensions.
  • Discover ERC721 extensions you may not have encountered before.
  • Understand what each extension does.

I hope the article serves as a useful reference. If you have any questions, feel free to reach out on Twitter.