ERC721

OpenZeppelinのERC721の取り扱い説明書

openZeppelin erc721
0xkeesmark

紹介しているOpenZeppelinのバージョンはv5.0.0

スマートコントラクトの中ではよく使われるERC721を紹介します。これはよくNFTで使われています。大体のNFTで使われている標準規格がERC721です。(こちらが規格の詳細EIP-721

まずERC721を使ってどうゆうことができるのかというと、

  • NFTを簡単に実装できる
  • 標準規格に沿った実装ができる

と結構シンプルですが、同じような実装を自分でしてしまうと、セキュリティ的にも大問題になりかねないので、シンプルにERC721を使うことをおすすめします。

ERC721とは?

OpenZeppelinのERC721は、EVM系のNFTを実装できます。OpenZeppelinライブラリは、このERC721の安全で標準に準拠した実装を提供してくれています。セキュリティ、効率性、および拡張性の高さが主な特徴です。

ERC721の中身

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.20;

import {IERC721} from "./IERC721.sol";
import {IERC721Receiver} from "./IERC721Receiver.sol";
import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {Strings} from "../../utils/Strings.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    mapping(uint256 tokenId => address) private _owners;

    mapping(address owner => uint256) private _balances;

    mapping(uint256 tokenId => address) private _tokenApprovals;

    mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual returns (uint256) {
        if (owner == address(0)) {
            revert ERC721InvalidOwner(address(0));
        }
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual returns (address) {
        return _requireOwned(tokenId);
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
        _requireOwned(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual {
        _approve(to, tokenId, _msgSender());
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual returns (address) {
        _requireOwned(tokenId);

        return _getApproved(tokenId);
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(address from, address to, uint256 tokenId) public virtual {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        // Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
        address previousOwner = _update(to, tokenId, _msgSender());
        if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
        transferFrom(from, to, tokenId);
        _checkOnERC721Received(from, to, tokenId, data);
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     *
     * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
     * core ERC721 logic MUST be matched with the use of {_increaseBalance} to keep balances
     * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
     * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
     */
    function _getApproved(uint256 tokenId) internal view virtual returns (address) {
        return _tokenApprovals[tokenId];
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
     * particular (ignoring whether it is owned by `owner`).
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
        return
            spender != address(0) &&
            (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
    }

    /**
     * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
     * Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets
     * the `spender` for the specific `tokenId`.
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
        if (!_isAuthorized(owner, spender, tokenId)) {
            if (owner == address(0)) {
                revert ERC721NonexistentToken(tokenId);
            } else {
                revert ERC721InsufficientApproval(spender, tokenId);
            }
        }
    }

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
     * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
     *
     * WARNING: Increasing an account's balance using this function tends to be paired with an override of the
     * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
     * remain consistent with one another.
     */
    function _increaseBalance(address account, uint128 value) internal virtual {
        unchecked {
            _balances[account] += value;
        }
    }

    /**
     * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
     * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that
     * `auth` is either the owner of the token, or approved to operate on the token (by the owner).
     *
     * Emits a {Transfer} event.
     *
     * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
     */
    function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
        address from = _ownerOf(tokenId);

        // Perform (optional) operator check
        if (auth != address(0)) {
            _checkAuthorized(from, auth, tokenId);
        }

        // Execute the update
        if (from != address(0)) {
            // Clear approval. No need to re-authorize or emit the Approval event
            _approve(address(0), tokenId, address(0), false);

            unchecked {
                _balances[from] -= 1;
            }
        }

        if (to != address(0)) {
            unchecked {
                _balances[to] += 1;
            }
        }

        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        return from;
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner != address(0)) {
            revert ERC721InvalidSender(address(0));
        }
    }

    /**
     * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        _checkOnERC721Received(address(0), to, tokenId, data);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal {
        address previousOwner = _update(address(0), tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        } else if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
     * are aware of the ERC721 standard to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is like {safeTransferFrom} in the sense that it invokes
     * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `tokenId` token must exist and be owned by `from`.
     * - `to` cannot be the zero address.
     * - `from` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId) internal {
        _safeTransfer(from, to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        _checkOnERC721Received(from, to, tokenId, data);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
     * either the owner of the token, or approved to operate on all tokens held by this owner.
     *
     * Emits an {Approval} event.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address to, uint256 tokenId, address auth) internal {
        _approve(to, tokenId, auth, true);
    }

    /**
     * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
     * emitted in the context of transfers.
     */
    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
        // Avoid reading the owner unless necessary
        if (emitEvent || auth != address(0)) {
            address owner = _requireOwned(tokenId);

            // We do not use _isAuthorized because single-token approvals should not be able to call approve
            if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
                revert ERC721InvalidApprover(auth);
            }

            if (emitEvent) {
                emit Approval(owner, to, tokenId);
            }
        }

        _tokenApprovals[tokenId] = to;
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Requirements:
     * - operator can't be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        if (operator == address(0)) {
            revert ERC721InvalidOperator(operator);
        }
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
     * Returns the owner.
     *
     * Overrides to ownership logic should be done to {_ownerOf}.
     */
    function _requireOwned(uint256 tokenId) internal view returns (address) {
        address owner = _ownerOf(tokenId);
        if (owner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
        return owner;
    }

    /**
     * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the
     * recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     */
    function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) private {
        if (to.code.length > 0) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                if (retval != IERC721Receiver.onERC721Received.selector) {
                    revert ERC721InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert ERC721InvalidReceiver(to);
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        }
    }
}

主要な関数をピックアップしていきます。(細々とした処理に関しての詳細は割愛します。)

storageとcontract

// トークンの名前
string private _name;

// トークンのシンボル
string private _symbol;
// トークンのオーナー  tokenId => owner address
mapping(uint256 tokenId => address) private _owners;
// オーナーのトークンの数 address => count
mapping(address owner => uint256) private _balances;
// tokenの承認者 tokenId => approved address
mapping(uint256 tokenId => address) private _tokenApprovals;
// 承認者のオペレーター owner => operator => bool
//  operatorはownerのトークンを操作できる
mapping(address owner => mapping(address operator => bool))
    private _operatorApprovals;

/**
 * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
 * @param name_ トークンの名前
 * @param symbol_ トークンのシンボル
 */
constructor(string memory name_, string memory symbol_) {
    _name = name_;
    _symbol = symbol_;
}
    

storageは必要最低限で構成されていて、constructorにはNFTの名前とシンボルを入れるだけのシンプルな作りになっています。

_update

/**
     * @param to 転送先のアドレス
     * @param tokenId 転送するトークンのID
     * @param auth 承認者のアドレス
     **/
    function _update(
        address to,
        uint256 tokenId,
        address auth
    ) internal virtual returns (address) {
        // トークンのオーナーを取得
        address from = _ownerOf(tokenId);

        // Perform (optional) operator check
        // 承認者がzeroアドレスでない場合、オーナーかオペレーターであることを確認する
        if (auth != address(0)) {
            _checkAuthorized(from, auth, tokenId);
        }

        // Execute the update
        // トークンのオーナーを更新
        // トークンのオーナーがzeroアドレスでない場合、オーナーのトークン数を減らす
        if (from != address(0)) {
            // Clear approval. No need to re-authorize or emit the Approval event
            // 承認をクリアする。再承認やApprovalイベントの発行は不要
            _approve(address(0), tokenId, address(0), false);

            // トークンのオーナーのトークン数を減らす
            unchecked {
                _balances[from] -= 1;
            }
        }

        // 転送先のアドレスがzeroアドレスでない場合、転送先のトークン数を増やす
        if (to != address(0)) {
            // トークンのオーナーのトークン数を増やす
            unchecked {
                _balances[to] += 1;
            }
        }

        // トークンのオーナー権を更新
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        return from;
    }

ここではトークンの所有権の譲渡などの処理を行うprivateな関数となってます。

ここでは主に3パターンでいろんな処理をすることができます。間違えて使ってしまうと危険なので、気を付けて使いましょう!

パターンto(転送先アドレス)tokenId(トークンのID)auth()
mintミントする相手のアドレス対象のトークンIDゼロアドレス
burnゼロアドレス対象のトークンIDゼロアドレス
所有者の変更転送先のアドレス対象のトークンID実行者のアドレス

実はこれ以外にも内部処理で所有者の変更を強制的にできたり、使い方次第ではいろんな処理を使うことをできるので、自分で_updateを使った処理を変更する場合は十分なテストを書くことを心がけましょう!

_mint(_safeMint)

OpenZepplineでは_mintを使うのは推奨しておらず、なるべく_safeMintの方を使ってねとのことなので、直接_mintを使うのはなるべく避けましょう!

ですが、_safeMintも_mintを内部で使用しているので、今回は_mintの中身も紹介します。

_mint

// @param to 転送先のアドレス
// @param tokenId 転送するトークンのID
function _mint(address to, uint256 tokenId) internal {
    // to が zeroアドレスの場合、revert
    if (to == address(0)) {
        revert ERC721InvalidReceiver(address(0));
    }
    // _updateでトークンのオーナーを更新&前回のオーナーを返す
    address previousOwner = _update(to, tokenId, address(0));
    // 前回のオーナーがzeroアドレスでない場合、revert
    if (previousOwner != address(0)) {
        revert ERC721InvalidSender(address(0));
    }
}

mintをする際には、転送先のアドレスが必須なのと、前のオーナーがゼロアドレス(所有者がいない)のが前提なので、その条件に一致しなかった場合はリバートされます。

_safeMint

function _safeMint(address to, uint256 tokenId) internal {
    // _safeMintを呼び出す
    _safeMint(to, tokenId, "");
}


function _safeMint(
    address to,
    uint256 tokenId,
    bytes memory data
) internal virtual {
    // _mintを呼び出してmintする
    _mint(to, tokenId);
    // _checkOnERC721Receivedを呼び出して、toがERC721を受け入れることを確認する
    _checkOnERC721Received(address(0), to, tokenId, data);
}

紛らわしいですが、上の_safeMintで下の_safeMintを呼んで処理をしていて、最終的にちゃんと受け取ったのかまでを確認します。

_burn

function _burn(uint256 tokenId) internal {
    // _updateへburnに必要な引数を渡す
    address previousOwner = _update(address(0), tokenId, address(0));
    // 前回のオーナーがzeroアドレスの場合、revert
    if (previousOwner == address(0)) {
        revert ERC721NonexistentToken(tokenId);
    }
}

burnする場合はこの関数を使用するのですが、この関数をそのまま使うと、tokenの所有者の意思に関係なくburnすることが可能になってしまうので、所有者のapproveが必要な仕様などの場合は、この前にapprovalを実行者が持っていることを確認するか、_updateを以下のようにする必要があります。

_update(address(0), tokenId, msg.sender);

transferFrom

transferFromに関しても受け取ったことを確認するsafeTransferFromもありますので、特に変わったことをしない場合はsafeTransferFromを使用することをおすすめします。

// @param from 転送元のアドレス
// @param to 転送先のアドレス
// @param tokenId 転送するトークンのID
function transferFrom(
    address from,
    address to,
    uint256 tokenId
) public virtual {
    // toがzeroアドレスの場合、revert
    if (to == address(0)) {
        revert ERC721InvalidReceiver(address(0));
    }
    // _updateでtoにtokenIdを転送する&実行者がapproveされているか確認する
    address previousOwner = _update(to, tokenId, _msgSender());
    // 前回のオーナーが from でない場合、revert
    if (previousOwner != from) {
        revert ERC721IncorrectOwner(from, tokenId, previousOwner);
    }
}

使い方

使い方は正直言って色々とあるので、今回はコントラクトのオーナーのみがmint&burnをできるという条件で最低限の実装します。

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

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MyNFT is ERC721, Ownable {
    uint256 private _nextTokenId;

    constructor(
        address initialOwner
    ) ERC721("MyNFT", "MN") Ownable(initialOwner) {}

    function safeMint(address to) public onlyOwner {
        uint256 tokenId = _nextTokenId++;
        _safeMint(to, tokenId);
    }

    function burn(uint256 tokenId) public onlyOwner {
        _update(address(0), tokenId, _msgSender());
    }
}

他にも色々とできたりするのですが、今回は超簡易の実装だけの紹介でした!

まとめ

OpenZeppelinのERC721は、NFTの作成と管理を簡単かつ標準化された方法実装できます。OpenZeppelinを使用する主な利点は、簡単にNFTを実装できることと、セキュリティが検証された方法でERC721の標準規格に準拠した実装ができることです。開発者が個々に同様の実装を行うとセキュリティリスクを抱える可能性があるため、OpenZeppelin使用することが推奨されます。今回は、コントラクトのオーナーのみがトークンを発行(mint)や消却(burn)できるような基本的な実装方法を紹介しましたが、OpenZeppelinではさまざまなカスタマイズが可能です。NFTを扱う際は、この堅牢で柔軟なERC721の実装を活用して、効率的かつ安全にプロジェクトを進めましょう。

ABOUT ME
0xkeesmark
0xkeesmark
Security Researcher
記事URLをコピーしました