概要

EIP3009は、オフチェーンで署名した承認付きトークン送付をチェーン上で検証・実行する仕組みを提供する抽象コントラクトです。 これにより、ガス抽象化やメタトランザクションと組み合わせて、送金者がガスを支払わずにトークンを移動できます。

EIP3009については以下の記事を参考にしてください。

  • TransferWithAuthorization
    • 署名者(authorizer)が指定した条件(有効開始時刻/期限、nonce)を満たす場合にのみトークンを送付します。
  • ReceiveWithAuthorization
    • 支払い先(payee)が署名付き転送を自ら呼び出すことで受け取れます。
    • フロントラン攻撃を防ぐため、to == msg.sender をチェックします。
  • CancelAuthorization
    • 未使用の署名付き転送を事前にキャンセルできます。

コード

text
/**
 * Copyright 2023 Circle Internet Group, Inc. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

pragma solidity 0.6.12;

import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol";
import { EIP712Domain } from "./EIP712Domain.sol";
import { SignatureChecker } from "../util/SignatureChecker.sol";
import { MessageHashUtils } from "../util/MessageHashUtils.sol";

/**
 * @title EIP-3009
 * @notice Provide internal implementation for gas-abstracted transfers
 * @dev Contracts that inherit from this must wrap these with publicly
 * accessible functions, optionally adding modifiers where necessary
 */
abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain {
    // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
    bytes32
        public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;

    // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
    bytes32
        public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;

    // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
    bytes32
        public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;

    /**
     * @dev authorizer address => nonce => bool (true if nonce is used)
     */
    mapping(address => mapping(bytes32 => bool)) private _authorizationStates;

    event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
    event AuthorizationCanceled(
        address indexed authorizer,
        bytes32 indexed nonce
    );

    /**
     * @notice Returns the state of an authorization
     * @dev Nonces are randomly generated 32-byte data unique to the
     * authorizer's address
     * @param authorizer    Authorizer's address
     * @param nonce         Nonce of the authorization
     * @return True if the nonce is used
     */
    function authorizationState(address authorizer, bytes32 nonce)
        external
        view
        returns (bool)
    {
        return _authorizationStates[authorizer][nonce];
    }

    /**
     * @notice Execute a transfer with a signed authorization
     * @param from          Payer's address (Authorizer)
     * @param to            Payee's address
     * @param value         Amount to be transferred
     * @param validAfter    The time after which this is valid (unix time)
     * @param validBefore   The time before which this is valid (unix time)
     * @param nonce         Unique nonce
     * @param v             v of the signature
     * @param r             r of the signature
     * @param s             s of the signature
     */
    function _transferWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        _transferWithAuthorization(
            from,
            to,
            value,
            validAfter,
            validBefore,
            nonce,
            abi.encodePacked(r, s, v)
        );
    }

    /**
     * @notice Execute a transfer with a signed authorization
     * @dev EOA wallet signatures should be packed in the order of r, s, v.
     * @param from          Payer's address (Authorizer)
     * @param to            Payee's address
     * @param value         Amount to be transferred
     * @param validAfter    The time after which this is valid (unix time)
     * @param validBefore   The time before which this is valid (unix time)
     * @param nonce         Unique nonce
     * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
     */
    function _transferWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        bytes memory signature
    ) internal {
        _requireValidAuthorization(from, nonce, validAfter, validBefore);
        _requireValidSignature(
            from,
            keccak256(
                abi.encode(
                    TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
                    from,
                    to,
                    value,
                    validAfter,
                    validBefore,
                    nonce
                )
            ),
            signature
        );

        _markAuthorizationAsUsed(from, nonce);
        _transfer(from, to, value);
    }

    /**
     * @notice Receive a transfer with a signed authorization from the payer
     * @dev This has an additional check to ensure that the payee's address
     * matches the caller of this function to prevent front-running attacks.
     * @param from          Payer's address (Authorizer)
     * @param to            Payee's address
     * @param value         Amount to be transferred
     * @param validAfter    The time after which this is valid (unix time)
     * @param validBefore   The time before which this is valid (unix time)
     * @param nonce         Unique nonce
     * @param v             v of the signature
     * @param r             r of the signature
     * @param s             s of the signature
     */
    function _receiveWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        _receiveWithAuthorization(
            from,
            to,
            value,
            validAfter,
            validBefore,
            nonce,
            abi.encodePacked(r, s, v)
        );
    }

    /**
     * @notice Receive a transfer with a signed authorization from the payer
     * @dev This has an additional check to ensure that the payee's address
     * matches the caller of this function to prevent front-running attacks.
     * EOA wallet signatures should be packed in the order of r, s, v.
     * @param from          Payer's address (Authorizer)
     * @param to            Payee's address
     * @param value         Amount to be transferred
     * @param validAfter    The time after which this is valid (unix time)
     * @param validBefore   The time before which this is valid (unix time)
     * @param nonce         Unique nonce
     * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
     */
    function _receiveWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        bytes memory signature
    ) internal {
        require(to == msg.sender, "FiatTokenV2: caller must be the payee");
        _requireValidAuthorization(from, nonce, validAfter, validBefore);
        _requireValidSignature(
            from,
            keccak256(
                abi.encode(
                    RECEIVE_WITH_AUTHORIZATION_TYPEHASH,
                    from,
                    to,
                    value,
                    validAfter,
                    validBefore,
                    nonce
                )
            ),
            signature
        );

        _markAuthorizationAsUsed(from, nonce);
        _transfer(from, to, value);
    }

    /**
     * @notice Attempt to cancel an authorization
     * @param authorizer    Authorizer's address
     * @param nonce         Nonce of the authorization
     * @param v             v of the signature
     * @param r             r of the signature
     * @param s             s of the signature
     */
    function _cancelAuthorization(
        address authorizer,
        bytes32 nonce,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        _cancelAuthorization(authorizer, nonce, abi.encodePacked(r, s, v));
    }

    /**
     * @notice Attempt to cancel an authorization
     * @dev EOA wallet signatures should be packed in the order of r, s, v.
     * @param authorizer    Authorizer's address
     * @param nonce         Nonce of the authorization
     * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
     */
    function _cancelAuthorization(
        address authorizer,
        bytes32 nonce,
        bytes memory signature
    ) internal {
        _requireUnusedAuthorization(authorizer, nonce);
        _requireValidSignature(
            authorizer,
            keccak256(
                abi.encode(CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce)
            ),
            signature
        );

        _authorizationStates[authorizer][nonce] = true;
        emit AuthorizationCanceled(authorizer, nonce);
    }

    /**
     * @notice Validates that signature against input data struct
     * @param signer        Signer's address
     * @param dataHash      Hash of encoded data struct
     * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
     */
    function _requireValidSignature(
        address signer,
        bytes32 dataHash,
        bytes memory signature
    ) private view {
        require(
            SignatureChecker.isValidSignatureNow(
                signer,
                MessageHashUtils.toTypedDataHash(_domainSeparator(), dataHash),
                signature
            ),
            "FiatTokenV2: invalid signature"
        );
    }

    /**
     * @notice Check that an authorization is unused
     * @param authorizer    Authorizer's address
     * @param nonce         Nonce of the authorization
     */
    function _requireUnusedAuthorization(address authorizer, bytes32 nonce)
        private
        view
    {
        require(
            !_authorizationStates[authorizer][nonce],
            "FiatTokenV2: authorization is used or canceled"
        );
    }

    /**
     * @notice Check that authorization is valid
     * @param authorizer    Authorizer's address
     * @param nonce         Nonce of the authorization
     * @param validAfter    The time after which this is valid (unix time)
     * @param validBefore   The time before which this is valid (unix time)
     */
    function _requireValidAuthorization(
        address authorizer,
        bytes32 nonce,
        uint256 validAfter,
        uint256 validBefore
    ) private view {
        require(
            now > validAfter,
            "FiatTokenV2: authorization is not yet valid"
        );
        require(now < validBefore, "FiatTokenV2: authorization is expired");
        _requireUnusedAuthorization(authorizer, nonce);
    }

    /**
     * @notice Mark an authorization as used
     * @param authorizer    Authorizer's address
     * @param nonce         Nonce of the authorization
     */
    function _markAuthorizationAsUsed(address authorizer, bytes32 nonce)
        private
    {
        _authorizationStates[authorizer][nonce] = true;
        emit AuthorizationUsed(authorizer, nonce);
    }
}

変数

solidity
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH

"TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)" の型ハッシュ。

solidity
bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH

"ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)" の型ハッシュ。

solidity
bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH

"CancelAuthorization(address authorizer,bytes32 nonce)" の型ハッシュ。

solidity
mapping(address => mapping(bytes32 => bool)) private _authorizationStates

各アドレス・ nonce の組み合わせが使用済み(true)かどうかを管理。

関数

authorizationState

solidity
function authorizationState(address authorizer, bytes32 nonce)
    external
    view
    returns (bool)
{
    return _authorizationStates[authorizer][nonce];
}

指定した authorizer と nonce の組み合わせが既に使用済みかを取得する関数。 内部マッピング _authorizationStates を参照し、真偽値を返します。

引数

  • authorizer
    • 署名者アドレス。
  • nonce
    • 署名付き転送の一意な識別子。

戻り値

  • bool
    • true
      • 既に使用済みまたはキャンセル済み
    • false
      • 未使用

_transferWithAuthorization(署名バイト列版)

solidity
function _transferWithAuthorization(
    address from,
    address to,
    uint256 value,
    uint256 validAfter,
    uint256 validBefore,
    bytes32 nonce,
    bytes memory signature
) internal {
    _requireValidAuthorization(from, nonce, validAfter, validBefore);
    _requireValidSignature(
        from,
        keccak256(
            abi.encode(
                TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
                from,
                to,
                value,
                validAfter,
                validBefore,
                nonce
            )
        ),
        signature
    );

    _markAuthorizationAsUsed(from, nonce);
    _transfer(from, to, value);
}

署名付き転送の検証と実行を行う関数。

  1. 有効期間と未使用状態の検証。
  2. EIP712型付きデータハッシュを生成して署名検証。
  3. 成功時に nonce を使用済みとしてマーク。
  4. ERC20._transfer で実際のトークン送付。

引数

  • from
    • 送金元アドレス。
  • to
    • 送金先アドレス。
  • value
    • 送付するトークン量。
  • validAfter
    • この送付が有効になる最早時間(Unix 時刻)
  • validBefore
    • この送付が有効である最遅時間(Unix 時刻)
  • nonce
    • 一意な識別子。
  • signature
    • r‖s‖v の順に連結された署名バイト列。

_transferWithAuthorization(v, r, s版)

solidity
function _transferWithAuthorization(
    address from,
    address to,
    uint256 value,
    uint256 validAfter,
    uint256 validBefore,
    bytes32 nonce,
    uint8 v,
    bytes32 r,
    bytes32 s
) internal {
    _transferWithAuthorization(
        from,
        to,
        value,
        validAfter,
        validBefore,
        nonce,
        abi.encodePacked(r, s, v)
    );
}

署名付き転送の検証と実行を行う関数(v, r, s 版)。

引数

  • from
    • 送金元アドレス。
  • to
    • 送金先アドレス。
  • value
    • 送付するトークン量。
  • validAfter
    • この送付が有効になる最早時間(Unix 時刻)
  • validBefore
    • この送付が有効である最遅時間(Unix 時刻)
  • nonce
    • 一意な識別子。
  • v
    • ECDSA署名の v 値。
  • r
    • ECDSA署名の r 値。
  • s
    • ECDSA署名の s 値。

_receiveWithAuthorization(署名バイト列版)

solidity
function _receiveWithAuthorization(
    address from,
    address to,
    uint256 value,
    uint256 validAfter,
    uint256 validBefore,
    bytes32 nonce,
    bytes memory signature
) internal {
    require(to == msg.sender, "FiatTokenV2: caller must be the payee");
    _requireValidAuthorization(from, nonce, validAfter, validBefore);
    _requireValidSignature(
        from,
        keccak256(
            abi.encode(
                RECEIVE_WITH_AUTHORIZATION_TYPEHASH,
                from,
                to,
                value,
                validAfter,
                validBefore,
                nonce
            )
        ),
        signature
    );

    _markAuthorizationAsUsed(from, nonce);
    _transfer(from, to, value);
}

受信者が送信者の署名を使用して、送信者から受信者へトークンを送付する関数。 フロントラン攻撃(※署名を第三者に盗まれて使用される)を防止するため、呼び出し元(msg.sender)が署名された to アドレス(=受信者)と一致する必要があります。

引数

  • from   - トークンの送信者アドレス(署名した本人)。
  • to   - トークンの受信者アドレス(呼び出し元と一致している必要があります)。
  • value   - 送付するトークンの数量。
  • validAfter   - この承認が有効になる時刻(Unix タイムスタンプ)。
  • validBefore   - この承認が無効になる期限時刻(Unix タイムスタンプ)。
  • nonce   - 承認メッセージを一意に識別するためのランダムな値。
  • signature   - from が署名した、承認データに対応する署名(r‖s‖v の順にバイト列でエンコード)。

_receiveWithAuthorization(v, r, s版)

solidity
function _receiveWithAuthorization(
    address from,
    address to,
    uint256 value,
    uint256 validAfter,
    uint256 validBefore,
    bytes32 nonce,
    uint8 v,
    bytes32 r,
    bytes32 s
) internal {
    _receiveWithAuthorization(
        from,
        to,
        value,
        validAfter,
        validBefore,
        nonce,
        abi.encodePacked(r, s, v)
    );
}

受信者が送信者の署名を使用して、送信者から受信者へトークンを送付する関数(v, r, s版)。 フロントラン攻撃(※署名を第三者に盗まれて使用される)を防止するため、呼び出し元(msg.sender)が署名された to アドレス(=受信者)と一致する必要があります。

引数

  • from   - トークンの送信者アドレス(署名した本人)。
  • to   - トークンの受信者アドレス(呼び出し元と一致している必要があります)。
  • value   - 送付するトークンの数量。
  • validAfter   - この承認が有効になる時刻(Unix タイムスタンプ)。
  • validBefore   - この承認が無効になる期限時刻(Unix タイムスタンプ)。
  • nonce   - 承認メッセージを一意に識別するためのランダムな値。
  • v
    • ECDSA署名の v 値。
  • r
    • ECDSA署名の r 値。
  • s
    • ECDSA署名の s 値。

_cancelAuthorization(署名バイト列版)

solidity
function _cancelAuthorization(
    address authorizer,
    bytes32 nonce,
    bytes memory signature
) internal {
    _requireUnusedAuthorization(authorizer, nonce);
    _requireValidSignature(
        authorizer,
        keccak256(
            abi.encode(CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce)
        ),
        signature
    );

    _authorizationStates[authorizer][nonce] = true;
    emit AuthorizationCanceled(authorizer, nonce);
}

署名されたキャンセル要求を検証し、その nonce を無効化する関数。 この関数は、まだ使用されていない署名付き転送を、署名者自身の意志でキャンセルする手段を提供します。 有効性チェック(未使用か/署名が正しいか)を行い、問題なければその nonce を「使用済み」としてマークして同じ転送が行われないようにします。 これにより署名の再利用(リプレイ)を防止できます。

引数

  • authorizer
    • 署名者のアドレス。
    • キャンセルを行う意思表示をしたアドレスです。
  • nonce
    • 署名付き転送に使われた一意な識別子。
    • この値を無効化します。
  • signature
    • CancelAuthorization(authorizer, nonce) に対する署名(EIP712準拠)。
    • 署名形式は r‖s‖v のバイト列です。

_cancelAuthorization(v, r, s パラメータ版)

solidity
function _cancelAuthorization(
    address authorizer,
    bytes32 nonce,
    uint8 v,
    bytes32 r,
    bytes32 s
) internal {
    _cancelAuthorization(authorizer, nonce, abi.encodePacked(r, s, v));
}

ECDSA 署名パーツ(v, r, s)を使って、署名バイト列を組み立てキャンセルを実行する関数。 この関数は、署名が v, r, s 形式で与えられた場合に、内部で abi.encodePacked(r, s, v) を使って署名バイト列に変換し、上記の署名バイト列版 _cancelAuthorization に委譲します。

引数

  • authorizer
    • 署名者アドレス。
  • nonce
    • キャンセル対象の nonce。
  • v
    • 署名の v 値(リカバリID)。
  • r
    • 署名の r 値(前半)。
  • s
    • 署名の s 値(後半)。

_requireValidSignature

solidity
function _requireValidSignature(
    address signer,
    bytes32 dataHash,
    bytes memory signature
) private view {
    require(
        SignatureChecker.isValidSignatureNow(
            signer,
            MessageHashUtils.toTypedDataHash(_domainSeparator(), dataHash),
            signature
        ),
        "FiatTokenV2: invalid signature"
    );
}

署名の有効性を検証する関数。

  • EIP712形式で署名されたデータかどうかを検証します。
  • toTypedDataHash() により、ドメインセパレータと構造化データハッシュ(dataHash)を結合し、署名メッセージハッシュを生成します。
  • SignatureChecker.isValidSignatureNow を使って signer が実際にこの署名を行ったかを検証します。
  • 無効な場合は revert します。

引数

  • signer
    • 検証対象の署名者アドレス。
  • dataHash
    • 署名対象の構造化データ(EIP712)に対するkeccak256ハッシュ。
  • signature
    • 署名バイト列(r‖s‖v の順にエンコード)。

_requireUnusedAuthorization

solidity
function _requireUnusedAuthorization(address authorizer, bytes32 nonce)
    private
    view
{
    require(
        !_authorizationStates[authorizer][nonce],
        "FiatTokenV2: authorization is used or canceled"
    );
}

署名付き承認が未使用であることを検証する関数。

  • 承認状態マッピング _authorizationStates を参照し、指定された (authorizer, nonce) がすでに使用済みか、キャンセルされている場合は revert します。
  • 未使用である場合のみ、処理を継続できます。

引数

  • authorizer
    • 承認を行った署名者アドレス。
  • nonce
    • 承認メッセージに対応する一意な識別子。

_requireValidAuthorization

solidity
function _requireValidAuthorization(
    address authorizer,
    bytes32 nonce,
    uint256 validAfter,
    uint256 validBefore
) private view {
    require(now > validAfter, "FiatTokenV2: authorization is not yet valid");
    require(now < validBefore, "FiatTokenV2: authorization is expired");
    _requireUnusedAuthorization(authorizer, nonce);
}

署名付き承認の有効期間および未使用性を検証する関数。

  • 現在のブロックタイム(now)が validAfter より後、かつ validBefore より前であることをチェックします。
  • また、nonce が未使用であることも _requireUnusedAuthorization を使って検証します。
  • いずれかが満たされない場合は revert します。

引数

  • authorizer
    • 承認を行った署名者アドレス。
  • nonce
    • 承認メッセージの一意識別子。
  • validAfter
    • 有効開始時刻(Unix 時刻)。
  • validBefore
    • 有効期限時刻(Unix 時刻)。

_markAuthorizationAsUsed

solidity
function _markAuthorizationAsUsed(address authorizer, bytes32 nonce)
    private
{
    _authorizationStates[authorizer][nonce] = true;
    emit AuthorizationUsed(authorizer, nonce);
}

指定された承認を「使用済み」として記録する関数。

  • _authorizationStates[authorizer][nonce] を true に設定し、使用済みの承認を再利用できないようにします。
  • その後、AuthorizationUsed イベントを発行して外部に通知します。

引数

  • authorizer
    • 承認を行った署名者アドレス。
  • nonce
    • 承認メッセージに対応する一意な識別子。