概要

このコントラクトは、Avalanche Interchain Token Transfer (ICTT) の「リモートチェーン」側で機能する、アップグレード可能なスマートコントラクトです。 連携するTokenHomeコントラクトから送られてきたトークンを、このチェーンのネイティブトークンとして表現します。 ネイティブトークンをMint(発行)するために、特別なプリコンパイルコントラクトを利用します。

アップグレードできないバージョンのコントラクトは以下です。

NativeTokenRemoteUpgradeableコントラクトは、ERC20TokenRemoteUpgradeableのネイティブトークン版です。 TokenHomeコントラクトからトークン送付のメッセージを受信すると、このコントラクトはチェーンに組み込まれたNativeMinterプリコンパイルを呼び出し、指定された量のネイティブトークンをMint(発行)して受取人に直接送付します。

逆に、ユーザーがこのチェーンのネイティブトークンをホームチェーンに戻す時は、ネイティブトークンをBURNED_FOR_TRANSFER_ADDRESSという特別なアドレスに送付することで、実質的なBurnとして扱います。

このコントラクトは2つ役割を備えています。

  • ICTTリモートコントラクト クロスチェーンでのネイティブトークンのMint(発行)とBurnを管理します。
  • Wrapped Native Token ユーザーが手動でネイティブトークンをラップ・アンラップするための標準的なインターフェース(deposit, withdraw)も提供します。 このコントラクト自体が、ラップされたERC20トークンとして機能します。

また、このチェーンでガス代としてBurnされたネイティブトークンの総量をTokenHomeコントラクトに報告し、システム全体の担保量を調整するreportBurnedTxFeesという機能を持ちます。

機能

このコントラクトの主要な機能は以下です。

  • ネイティブトークンのMint(発行) TokenHomeからのメッセージに基づき、NativeMinterプリコンパイルを通じてネイティブトークンをMint(発行)します。
  • ネイティブトークンのBurn トークンを他のチェーンへ送付する時、ネイティブトークンを特定のBurn用アドレスへ送付します。
  • Burn済み手数料の報告 このチェーンのシステム全体でガス代としてBurnされた手数料をTokenHomeに報告し、担保量を調整させます。
  • Wrapped Native Token機能 ユーザーがネイティブトークンをこのコントラクト(ERC20トークンとして機能)にラップしたり、アンラップしたりできます。

フロー

  • ネイティブトークンの受信とMint(発行) (_withdraw)
  • ネイティブトークンの送付(Burn)
  • Burn済み手数料の報告 (reportBurnedTxFees)
  • ネイティブトークンのラップ (deposit)
  • ラップされたトークンのアンラップ (withdraw)

ネイティブトークンの受信とMint(発行) (_withdraw)

sequenceDiagram
    participant TH as TokenHome
    participant TP as Teleporter
    participant NTRU as NativeTokenRemoteUpgradeable
    participant NM as NativeMinter Precompile
    participant Recipient as 受取人
    
    TH->>TP: メッセージを送信
    TP->>NTRU: _receiveTeleporterMessage(...)
    NTRU->>NTRU: _withdraw(Recipient, amount) を呼び出し
    NTRU->>NTRU: TokensWithdrawn イベントを発行
    NTRU->>NTRU: _mintNativeCoin(Recipient, amount)
    NTRU->>NM: mintNativeCoin(Recipient, amount)
    NM-->>Recipient: ネイティブトークン残高が増加

ネイティブトークンの送付(Burn)

sequenceDiagram
    participant User as ユーザー
    participant NTRU as NativeTokenRemoteUpgradeable
    participant BurnAddr as BURNED_FOR_TRANSFER_ADDRESS
    participant TR as TokenRemote (親)

    User->>NTRU: send(input) with msg.value
    NTRU->>TR: _send(input, msg.value)
    TR->>NTRU: _burn(msg.value) を呼び出し
    NTRU->>BurnAddr: msg.value のネイティブトークンを送付

Burn済み手数料の報告 (reportBurnedTxFees)

sequenceDiagram
    participant Relayer as リレイヤー
    participant NTRU as NativeTokenRemoteUpgradeable
    participant FeeBurnAddr as BURNED_TX_FEES_ADDRESS
    participant NM as NativeMinter Precompile
    participant TP as Teleporter

    Relayer->>NTRU: reportBurnedTxFees(...)
    NTRU->>FeeBurnAddr: balance を確認
    NTRU->>NTRU: 報酬額と報告額を計算
    NTRU->>NM: mintNativeCoin(this, reward)
    NTRU->>NTRU: _mint(this, reward) (ERC20としてラップ)
    NTRU->>NTRU: SINGLE_HOP_SEND メッセージを構築
    NTRU->>TP: _sendTeleporterMessage(...)

ネイティブトークンのラップ (deposit)

sequenceDiagram
    participant User as ユーザー
    participant NTRU as NativeTokenRemoteUpgradeable
    
    User->>NTRU: ネイティブトークンを送付 (msg.value)
    NTRU->>NTRU: deposit()
    NTRU->>NTRU: Deposit イベントを発行
    NTRU->>NTRU: _mint(User, msg.value) (ERC20 Mint)

ラップされたトークンのアンラップ (withdraw)

sequenceDiagram
    participant User as ユーザー
    participant NTRU as NativeTokenRemoteUpgradeable
    
    User->>NTRU: withdraw(amount)
    NTRU->>NTRU: Withdrawal イベントを発行
    NTRU->>NTRU: _burn(User, amount) (ERC20 Burn)
    NTRU->>User: ネイティブトークンを送付 (sendValue)

コード

構造体

NativeTokenRemoteStorage

text
struct NativeTokenRemoteStorage {
    /**
     * @notice Percentage of burned transaction fees that will be rewarded to a relayer delivering
     * the message created by calling calling reportBurnedTxFees().
     */
    uint256 _burnedFeesReportingRewardPercentage;
    /**
     * @notice Total number of tokens minted by this contract through the native minter precompile.
     */
    uint256 _totalMinted;
    /**
     * @notice The balance of BURNED_TX_FEES_ADDRESS the last time burned fees were reported to the TokenHome instance.
     */
    uint256 _lastestBurnedFeesReported;
}

ERC7201規格に準拠した、アップグレード時のストレージ衝突を防ぐための名前空間ストレージ構造体。 このコントラクトの主要な変数をすべて含みます。

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

  • _burnedFeesReportingRewardPercentage Burn済み手数料を報告したrelayerに与えられる報酬の割合(パーセンテージ)。
  • _totalMinted このコントラクトがNativeMinterプリコンパイルを通じてMint(発行)したネイティブトークンの総量。
  • _lastestBurnedFeesReported 最後にreportBurnedTxFeesが呼ばれた時の、BURNED_TX_FEES_ADDRESSの残高。

変数

NATIVE_TOKEN_REMOTE_STORAGE_LOCATION

text
bytes32 public constant NATIVE_TOKEN_REMOTE_STORAGE_LOCATION =
    0x69a5f7616543528c4fbe43f410b1034bd6da4ba06c25bedf04617268014cf500;

NativeTokenRemoteStorage構造体を格納するストレージスロットの位置を示す定数。 ERC7201規格で定められた計算式に基づいて算出された固定値です。

BURNED_TX_FEES_ADDRESS

text
address public constant BURNED_TX_FEES_ADDRESS = 0x0100000000000000000000000000000000000000;

トランザクション手数料としてBurnされたネイティブトークンが送られるシステム予約アドレス。 このアドレスの残高を読み取ることで、チェーン全体でBurnされたガス代の総量がわかります。

BURNED_FOR_TRANSFER_ADDRESS

text
address public constant BURNED_FOR_TRANSFER_ADDRESS = 0x0100000000000000000000000000000000010203;

他のチェーンへトークンを送付する時に、Burnの代わりにネイティブトークンが送付されるアドレス。BURNED_TX_FEES_ADDRESSとは別のアドレスにすることで、ガス代としてのBurnと送付のためのBurnを区別して追跡できます。

HOME_CHAIN_BURN_ADDRESS

text
address public constant HOME_CHAIN_BURN_ADDRESS = 0x0100000000000000000000000000000000010203;

reportBurnedTxFees関数がTokenHomeコントラクトへメッセージを送る時の、受取人アドレスとして使用されるダミーのアドレス。 TokenHome側でこのアドレスへの送付として処理されることで、実質的に対応する担保がBurnされたことになります。

NATIVE_MINTER

text
INativeMinter public constant NATIVE_MINTER =
    INativeMinter(0x0200000000000000000000000000000000000001);

ネイティブトークンをMint(発行)する機能を持つ、チェーンに組み込まれたプリコンパイルコントラクトのアドレス。

イベント

ReportBurnedTxFees

text
event ReportBurnedTxFees(bytes32 indexed teleporterMessageID, uint256 feesBurned);

reportBurnedTxFees関数が実行され、Burn済み手数料の報告メッセージが送信された時に発行されるイベント。

Modifier

onlyWhenCollateralized

text
/**
 * @dev When modifier is used, the function can only be called after the contract is fully collelateralized,
 * accounting for the initialReserveImbalance.
 */
modifier onlyWhenCollateralized() {
    require(getIsCollateralized(), "NativeTokenRemote: contract undercollateralized");
    _;
}

このModifierが付与された関数は、コントラクトが完全に担保された後(_isCollateralizedフラグがtrueになった後)にのみ実行可能となります。 これにより、初期担保が満たされる前にユーザーがトークンを送付してしまうことを防ぎます。

関数

_getNativeTokenRemoteStorage

text
// solhint-disable ordering
function _getNativeTokenRemoteStorage()
    private
    pure
    returns (NativeTokenRemoteStorage storage $)
{
    // solhint-disable-next-line no-inline-assembly
    assembly {
        $.slot := NATIVE_TOKEN_REMOTE_STORAGE_LOCATION
    }
}

NativeTokenRemoteStorage構造体へのストレージポインタを取得する内部関数。

インラインアセンブリを使用し、定数NATIVE_TOKEN_REMOTE_STORAGE_LOCATIONで指定されたストレージスロットを読み込むことで、NativeTokenRemoteStorage構造体への参照を返します。 これにより、効率的かつ安全にアップグレード可能なストレージ領域にアクセスできます。

戻り値

  • NativeTokenRemoteStorage storage $ NativeTokenRemoteStorage構造体へのストレージポインタ。

constructor

text
constructor(
    ICMInitializable init
) {
    if (init == ICMInitializable.Disallowed) {
        _disableInitializers();
    }
}

コントラクトの初期化を制御するための初期化関数。

このconstructorは、このコントラクトを継承するアップグレードできないバージョンのコントラクトが、initialize関数を複数回呼び出せないように制御するために存在します。 引数initにDisallowedが渡された時、_disableInitializersを呼び出してinitialize関数の実行を永久に禁止します。

sequenceDiagram
    participant Deployer as デプロイ者
    participant Self as NativeTokenRemoteUpgradeable
    
    Deployer->>Self: constructor(init)
    alt init is Disallowed
        Self->>Self: _disableInitializers()
    end

引数

  • init ICMInitializable型のenum値で、初期化を許可するかどうかを示します。

initialize

text
/**
 * @notice Initializes this token TokenRemote instance to receive tokens from the specified TokenHome instance,
 * and represents the received tokens with the native token on this chain.
 * @param settings Constructor settings for this token TokenRemote instance.
 * @param nativeAssetSymbol The symbol of the native asset.
 * @param initialReserveImbalance The initial reserve imbalance that must be collateralized before minting.
 * @param burnedFeesReportingRewardPercentage The percentage of burned transaction fees
 * that will be rewarded to sender of the report.
 */
function initialize(
    TokenRemoteSettings memory settings,
    string memory nativeAssetSymbol,
    uint256 initialReserveImbalance,
    uint256 burnedFeesReportingRewardPercentage
) public initializer {
    __NativeTokenRemote_init(
        settings,
        nativeAssetSymbol,
        initialReserveImbalance,
        burnedFeesReportingRewardPercentage
    );
}

アップグレード可能なコントラクトとして初期設定を行うための関数。

constructorの代わりに使用される初期化関数です。 initializer Modifierにより、この関数が一度しか呼び出されないことが保証されます。 内部で__NativeTokenRemote_initを呼び出し、コントラクトの初期設定をすべて行います。

sequenceDiagram
    participant Owner as オーナー
    participant Self as NativeTokenRemoteUpgradeable
    
    Owner->>Self: initialize(...)
    Self->>Self: __NativeTokenRemote_init(...)

引数

  • settings Teleporter関連のアドレスや連携するTokenHomeコントラクトの情報を含むTokenRemoteSettings構造体。
  • nativeAssetSymbol このチェーンのネイティブトークンのシンボル。
  • initialReserveImbalance 担保のない初期トークン供給量。
  • burnedFeesReportingRewardPercentage Burn済み手数料を報告したrelayerに与えられる報酬の割合。

__NativeTokenRemote_init

text
// solhint-disable-next-line func-name-mixedcase
function __NativeTokenRemote_init(
    TokenRemoteSettings memory settings,
    string memory nativeAssetSymbol,
    uint256 initialReserveImbalance,
    uint256 burnedFeesReportingRewardPercentage
) internal onlyInitializing {
    require(initialReserveImbalance != 0, "NativeTokenRemote: zero initial reserve imbalance");
    __ERC20_init(nativeAssetSymbol, nativeAssetSymbol);
    __TokenRemote_init(settings, initialReserveImbalance, 18);
    __NativeTokenRemote_init_unchained(burnedFeesReportingRewardPercentage);
}

このコントラクトと親コントラクトの初期化ロジックをまとめて実行する内部関数。

onlyInitializing Modifierで保護されています。 __ERC20_initを呼び出してこのコントラクトをERC20トークン(ラップされたトークン)として初期化し、__TokenRemote_initを呼び出してICTTのリモートコントラクトとしての設定を行います。 最後に__NativeTokenRemote_init_unchainedを呼び出してこのコントラクトの変数を初期化します。

sequenceDiagram
    participant Caller as initialize()
    participant Self as NativeTokenRemoteUpgradeable
    participant ParentERC20 as ERC20Upgradeable
    participant ParentRemote as TokenRemote
    
    Caller->>Self: __NativeTokenRemote_init(...)
    Self->>Self: initialReserveImbalance != 0 を検証
    Self->>ParentERC20: __ERC20_init(symbol, symbol)
    Self->>ParentRemote: __TokenRemote_init(settings, imbalance, 18)
    Self->>Self: __NativeTokenRemote_init_unchained(...)

引数

  • settings TokenRemoteSettings構造体。
  • nativeAssetSymbol ネイティブトークンのシンボル。
  • initialReserveImbalance 担保のない初期トークン供給量。
  • burnedFeesReportingRewardPercentage Burn済み手数料の報告に対する報酬の割合。

__NativeTokenRemote_init_unchained

text
// solhint-disable-next-line func-name-mixedcase
function __NativeTokenRemote_init_unchained(
    uint256 burnedFeesReportingRewardPercentage
) internal onlyInitializing {
    require(burnedFeesReportingRewardPercentage < 100, "NativeTokenRemote: invalid percentage");
    _getNativeTokenRemoteStorage()._burnedFeesReportingRewardPercentage =
        burnedFeesReportingRewardPercentage;
}

このコントラクトの変数を初期化するための内部関数。

onlyInitializing Modifierで保護されています。 報酬の割合が100未満であることを検証した後、_getNativeTokenRemoteStorageを呼び出してストレージ構造体を取得し、_burnedFeesReportingRewardPercentage変数を設定します。

sequenceDiagram
    participant Caller as __NativeTokenRemote_init()
    participant Self as NativeTokenRemoteUpgradeable
    
    Caller->>Self: __NativeTokenRemote_init_unchained(...)
    Self->>Self: burnedFeesReportingRewardPercentage を検証
    Self->>Self: _getNativeTokenRemoteStorage()
    Self->>Self: _burnedFeesReportingRewardPercentage 変数を保存

引数

  • burnedFeesReportingRewardPercentage Burn済み手数料の報告に対する報酬の割合。

receive

text
/**
 * @dev Receives native token with no calldata provided. The tokens are credited to the sender's
 * wrapped native token balance.
 */
receive() external payable {
    deposit();
}

ネイティブトークンを受け取り、ラップされたトークン残高に加算する関数。

関数を指定せずに、このコントラクトアドレスへ直接ネイティブトークンが送付された時に実行されます。 内部でdeposit関数を呼び出し、送られてきたネイティブトークンを送信者のラップされたトークン(このコントラクトのERC20残高)に変換します。

fallback

text
/**
 * @dev Fallback function for receiving native tokens. The tokens are credited to the sender's
 * wrapped native token balance.
 */
fallback() external payable {
    deposit();
}

ネイティブトークンを受け取るためのフォールバック関数。

存在しない関数が呼び出された時に実行されます。 このコントラクトでは、receiveと同様にdeposit関数を呼び出し、送られてきたネイティブトークンをラップします。

send

text
/**
 * @dev See {INativeTokenTransferrer-send}.
 */
function send(
    SendTokensInput calldata input
) external payable onlyWhenCollateralized {
    _send(input, msg.value);
}

リモートチェーンにネイティブトークンを送付するための関数。

onlyWhenCollateralized Modifierにより、コントラクトが完全に担保された後でのみ実行可能です。 payable修飾子でネイティブトークンを受け取り、その量 (msg.value) をamountとして、親コントラクトの_send関数を呼び出します。

sequenceDiagram
    participant User as ユーザー
    participant Self as NativeTokenRemoteUpgradeable
    participant Parent as TokenRemote
    
    User->>Self: send(input) with msg.value
    Self->>Self: onlyWhenCollateralized Modifierを実行
    Self->>Parent: _send(input, msg.value)
  • input 送付先チェーンID、受取人アドレスなどを含むSendTokensInput構造体。

sendAndCall

text
/**
 * @dev See {INativeTokenTransferrer-sendAndCall}
 */
function sendAndCall(
    SendAndCallInput calldata input
) external payable onlyWhenCollateralized {
    _sendAndCall(input, msg.value);
}

トークンを送付して送付先チェーンのコントラクトを呼び出すための関数。

onlyWhenCollateralized Modifierで保護されています。 payableでネイティブトークンを受け取り、その量 (msg.value) をamountとして、親コントラクトの_sendAndCall関数を呼び出します。

sequenceDiagram
    participant User as ユーザー
    participant Self as NativeTokenRemoteUpgradeable
    participant Parent as TokenRemote
    
    User->>Self: sendAndCall(input) with msg.value
    Self->>Self: onlyWhenCollateralized Modifierを実行
    Self->>Parent: _sendAndCall(input, msg.value)

引数

  • input 宛先コントラクトアドレス、ガスリミット、呼び出しデータなどを含むSendAndCallInput構造体。

reportBurnedTxFees

text
/**
 * @dev See {INativeTokenRemote-reportBurnedTxFees}.
 */
function reportBurnedTxFees(
    uint256 requiredGasLimit
) external sendNonReentrant {
    NativeTokenRemoteStorage storage $ = _getNativeTokenRemoteStorage();
    uint256 burnAddressBalance = BURNED_TX_FEES_ADDRESS.balance;
    require(
        burnAddressBalance > $._lastestBurnedFeesReported,
        "NativeTokenRemote: burn address balance not greater than last report"
    );

    uint256 burnedDifference = burnAddressBalance - $._lastestBurnedFeesReported;
    uint256 reward = (burnedDifference * $._burnedFeesReportingRewardPercentage) / 100;
    uint256 burnedTxFees = burnedDifference - reward;
    $._lastestBurnedFeesReported = burnAddressBalance;

    if (reward > 0) {
        // Re-mint the native tokens to this contract, and then deposit them to be the wrapped
        // native token (ERC20) representation, such that they can be used as a Teleporter
        // message fee.
        _mintNativeCoin(address(this), reward);
        _mint(address(this), reward);
    }

    // Check that the scaled amount on the TokenHome instance will be non-zero.
    require(
        TokenScalingUtils.removeTokenScale(
            getTokenMultiplier(), getMultiplyOnRemote(), burnedTxFees
        ) > 0,
        "NativeTokenRemote: zero scaled amount to report burn"
    );

    // Report the burned amount to the TokenHome instance.
    TransferrerMessage memory message = TransferrerMessage({
        messageType: TransferrerMessageType.SINGLE_HOP_SEND,
        payload: abi.encode(
            SingleHopSendMessage({recipient: HOME_CHAIN_BURN_ADDRESS, amount: burnedTxFees})
        )
    });

    bytes32 messageID = _sendTeleporterMessage(
        TeleporterMessageInput({
            destinationBlockchainID: getTokenHomeBlockchainID(),
            destinationAddress: getTokenHomeAddress(),
            feeInfo: TeleporterFeeInfo({feeTokenAddress: address(this), amount: reward}),
            requiredGasLimit: requiredGasLimit,
            allowedRelayerAddresses: new address[](0),
            message: abi.encode(message)
        })
    );

    emit ReportBurnedTxFees({teleporterMessageID: messageID, feesBurned: burnedTxFees});
}

このチェーンでBurnされたガス代の総量をTokenHomeコントラクトに報告する関数。

sendNonReentrant Modifierで保護されています。 まず、予約アドレスであるBURNED_TX_FEES_ADDRESSの現在の残高を取得し、前回報告時の残高との差分を計算します。 差分から、設定された割合に基づいて報告者(relayer)への報酬額を算出します。 報酬がある場合、_mintNativeCoinで報酬分のネイティブトークンをこのコントラクトにMint(発行)し、さらに_mintでERC20としてラップします。 これにより、報酬をTeleporterメッセージの手数料として使用できます。 報酬を差し引いたBurn済み手数料の額をペイロードとするSINGLE_HOP_SENDメッセージを構築し、TokenHomeコントラクトへ送信します。 この時、受取人はダミーのHOME_CHAIN_BURN_ADDRESSに設定されます。 最後にReportBurnedTxFeesイベントを発行します。

sequenceDiagram
    participant Relayer as 報告者
    participant Self as NativeTokenRemoteUpgradeable
    participant FeeBurnAddr as BURNED_TX_FEES_ADDRESS
    participant NM as NativeMinter Precompile
    participant TP as Teleporter

    Relayer->>Self: reportBurnedTxFees(...)
    Self->>FeeBurnAddr: balance を確認
    Self->>Self: 差分、報酬額、報告額を計算
    Self->>Self: _lastestBurnedFeesReported を更新
    opt reward > 0
        Self->>NM: mintNativeCoin(this, reward)
        Self->>Self: _mint(this, reward) (ERC20としてラップ)
    end
    Self->>Self: 報告額が0より大きいか検証
    Self->>Self: SINGLE_HOP_SEND メッセージを構築
    Self->>TP: _sendTeleporterMessage(...)
    TP-->>Self: messageID を返す
    Self->>Self: ReportBurnedTxFees イベントを発行

引数

  • requiredGasLimit この報告メッセージをTokenHomeコントラクトで実行するために必要なガスリミット。

withdraw

text
/**
 * @dev See {IWrappedNativeToken-withdraw}.
 *
 * Note: {IWrappedNativeToken-withdraw} should not be confused with {TokenRemote-_withdraw}.
 * {IWrappedNativeToken-withdraw} is the external method to redeem a wrapped native token (ERC20) balance
 * for the native token itself. {TokenRemote-_withdraw} is the internal method used when
 * processing token transfers.
 */
function withdraw(
    uint256 amount
) external {
    emit Withdrawal(_msgSender(), amount);
    _burn(_msgSender(), amount);
    payable(_msgSender()).sendValue(amount);
}

ラップされたトークン(このコントラクトのERC20残高)をネイティブトークンにアンラップする関数。

IWrappedNativeTokenインターフェースの実装です。 まずWithdrawalイベントを発行し、_burnを呼び出して関数実行者のERC20残高をamount分だけBurnします。 最後に、同量のネイティブトークンをsendValueを使って関数実行者に送金します。

sequenceDiagram
    participant User as ユーザー
    participant Self as NativeTokenRemoteUpgradeable
    
    User->>Self: withdraw(amount)
    Self->>Self: Withdrawal イベントを発行
    Self->>Self: _burn(User, amount) (ERC20 Burn)
    Self->>User: sendValue(amount)

引数

  • amount アンラップしたいトークンの量。

deposit

text
/**
 * @dev See {IWrappedNativeToken-deposit}.
 */
function deposit() public payable {
    emit Deposit(_msgSender(), msg.value);
    _mint(_msgSender(), msg.value);
}

ネイティブトークンをラップして、このコントラクトのERC20残高に変換する関数。

IWrappedNativeTokenインターフェースの実装です。 payableでネイティブトークンを受け取り、Depositイベントを発行します。 次に_mintを呼び出して、受け取ったネイティブトークンと同量のERC20トークンを関数実行アドレスにMint(発行)します。

sequenceDiagram
    participant User as ユーザー
    participant Self as NativeTokenRemoteUpgradeable
    
    User->>Self: deposit() with msg.value
    Self->>Self: Deposit イベントを発行
    Self->>Self: _mint(User, msg.value) (ERC20 Mint)

totalNativeAssetSupply

text
/**
 * @dev See {INativeTokenRemote-totalNativeAssetSupply}.
 *
 * Note: {INativeTokenRemote-totalNativeAssetSupply} should not be confused with {IERC20-totalSupply}
 * {INativeTokenRemote-totalNativeAssetSupply} returns the supply of the native asset of the chain,
 * accounting for the amounts that have been transferred in and out of the chain as well as burnt transaction
 * fees. The {initialReserveBalance} is included in this supply since it is in circulation on this
 * chain even prior to it being backed by collateral on the TokenHome instance.
 * {IERC20-totalSupply} returns the supply of the native asset held by this contract
 * that is represented as an ERC20.
 */
function totalNativeAssetSupply() public view returns (uint256) {
    NativeTokenRemoteStorage storage $ = _getNativeTokenRemoteStorage();
    uint256 burned = BURNED_TX_FEES_ADDRESS.balance + BURNED_FOR_TRANSFER_ADDRESS.balance;
    uint256 created = $._totalMinted + getInitialReserveImbalance();
    return created - burned;
}

このチェーン上のネイティブトークンの理論上の総供給量を計算して返す関数。

このチェーンのネイティブトークン供給量を、ICTTの観点から計算します。 総供給量は (このコントラクトがMintした総量 + 担保のない初期供給量) - (ガス代としてBurnされた総量 + 送付のためにBurnされた総量) として計算されます。 IERC20-totalSupplyがラップされたトークンの供給量を返すのとは対照的に、この関数はチェーン全体のネイティブトークン供給量を返します。

この関数が返す値が「理論上」なのは、このコントラクトが把握できる範囲でのみ供給量を計算しているためです。 この計算は、あくまで供給量の上限値を示します。 例えば、ユーザーが0x...deadのような、誰も秘密鍵を知らないアドレスにネイティブトークンを送付して実質的にBurnした場合、このコントラクトはその量を追跡できません。 そのため、実際の流通量は、この関数が返す値よりも少なくなる可能性があります。 IERC20を継承しているコントラクトのtotalSupplyがラップされたトークンの供給量を返すのとは対照的に、この関数はチェーン全体のネイティブトークン供給量を返します。

戻り値

  • uint256 理論上のネイティブトークン総供給量。

getTotalMinted

text
function getTotalMinted() external view returns (uint256) {
    return _getNativeTokenRemoteStorage()._totalMinted;
}

このコントラクトがNativeMinterプリコンパイルを通じてMint(発行)したネイティブトークンの総量を返す関数。

変数_totalMintedの値を返します。

戻り値

  • uint256 Mint(発行)されたネイティブトークンの総量。

_withdraw

text
/**
 * @dev See {TokenRemote-_withdraw}
 */
function _withdraw(address recipient, uint256 amount) internal virtual override {
    emit TokensWithdrawn(recipient, amount);
    _mintNativeCoin(recipient, amount);
}

ネイティブトークンをMint(発行)して受取人のアドレスに送付する内部関数。

親コントラクトTokenRemoteの同名関数をオーバーライドしています。 _receiveTeleporterMessageから呼び出されると、TokensWithdrawnイベントを発行し、内部ヘルパー関数_mintNativeCoinを呼び出して、指定されたrecipientにamount分のネイティブトークンをMint(発行)します。

sequenceDiagram
    participant Caller as 親コントラクト (TokenRemote)
    participant Self as NativeTokenRemoteUpgradeable
    
    Caller->>Self: _withdraw(recipient, amount)
    Self->>Self: TokensWithdrawn イベントを発行
    Self->>Self: _mintNativeCoin(recipient, amount)

引数

  • recipient ネイティブトークンを受け取るアドレス。
  • amount Mint(発行)するトークンの量。

_burn

text
/**
 * @dev See {TokenRemote-_burn}
 *
 * This is the internal {_burn} method called when transferring tokens to another chain.
 * The tokens to be burnt are already held by this contract. To burn the tokens, send the
 * native token amount to the BURNED_FOR_TRANSFER_ADDRESS.
 */
function _burn(
    uint256 amount
) internal virtual override returns (uint256) {
    payable(BURNED_FOR_TRANSFER_ADDRESS).sendValue(amount);
    return amount;
}

送付を開始するためにネイティブトークンをBurn(相当の処理)するための内部関数。

親コントラクトTokenRemoteの同名関数をオーバーライドしています。 送付処理の最初に呼び出されます。 ネイティブトークンはBurnできないため、代わりにamount分のネイティブトークンをBURNED_FOR_TRANSFER_ADDRESSに送金することで、実質的なBurnとして扱います。

sequenceDiagram
    participant Caller as 親コントラクト (TokenRemote)
    participant Self as NativeTokenRemoteUpgradeable
    participant BurnAddr as BURNED_FOR_TRANSFER_ADDRESS
    
    Caller->>Self: _burn(amount)
    Self->>BurnAddr: sendValue(amount)
    Self-->>Caller: amount を返す

引数

  • amount Burnするネイティブトークンの量。

戻り値

  • uint256 実際にBurnされた(送金された)量。

_handleSendAndCall

text
/**
 * @dev See {TokenRemote-_handleSendAndCall}
 *
 * Mints the tokens to this contract, and send them to the recipient contract as a
 * part of the call to {INativeSendAndCallReceiver-receiveTokens} on the recipient contract.
 * If the call fails, the amount is sent to the fallback recipient.
 *
 * Note: If the recipient contract does not properly handle the full msg.value sent,
 * the balance can be locked in the recipient contract. Receiving contracts must make
 * sure to properly handle the balance to ensure it does not get locked improperly.
 */
function _handleSendAndCall(
    SingleHopCallMessage memory message,
    uint256 amount
) internal virtual override {
    // Mint the tokens to this contract address.
    _mintNativeCoin(address(this), amount);

    // Encode the call to {INativeSendAndCallReceiver-receiveTokens}
    bytes memory payload = abi.encodeCall(
        INativeSendAndCallReceiver.receiveTokens,
        (
            message.sourceBlockchainID,
            message.originTokenTransferrerAddress,
            message.originSenderAddress,
            message.recipientPayload
        )
    );

    // Call the recipient contract with the given payload, gas amount, and value.
    bool success = CallUtils._callWithExactGasAndValue(
        message.recipientGasLimit, amount, message.recipientContract, payload
    );

    // If the call failed, send the funds to the fallback recipient.
    if (success) {
        emit CallSucceeded(message.recipientContract, amount);
    } else {
        emit CallFailed(message.recipientContract, amount);
        payable(message.fallbackRecipient).sendValue(amount);
    }
}

「送付とコントラクト呼び出し」メッセージを処理するための内部関数。

親コントラクトの同名関数をオーバーライドしています。 まず_mintNativeCoinを呼び出し、このコントラクト自身のアドレスにamount分のネイティブトークンをMint(発行)します。 次に、receiveTokensを呼び出すためのペイロードを構築し、_callWithExactGasAndValueを使って、Mintしたネイティブトークン (amount) をmsg.valueとして宛先コントラクトを呼び出します。 呼び出しが成功すればCallSucceededイベントを、失敗すればCallFailedイベントを発行し、ネイティブトークンをフォールバックアドレスに送金します。

sequenceDiagram
    participant Caller as 親コントラクト (TokenRemote)
    participant Self as NativeTokenRemoteUpgradeable
    participant NM as NativeMinter Precompile
    participant Recipient as 宛先コントラクト
    participant Fallback as フォールバックアドレス
    
    Caller->>Self: _handleSendAndCall(message, amount)
    Self->>NM: mintNativeCoin(this, amount)
    Self->>Self: receiveTokens(...) のペイロードを構築
    Self->>Recipient: _callWithExactGasAndValue(gas, amount, payload)
    Recipient-->>Self: 成功/失敗 (success)
    alt success
        Self->>Self: CallSucceeded イベントを発行
    else
        Self->>Self: CallFailed イベントを発行
        Self->>Fallback: sendValue(amount)
    end

引数

  • message 呼び出し先情報などを含むメッセージ構造体。
  • amount 利用可能なトークンの量。

_handleFees

text
/**
 * @notice See {TokenRemote-_handleFees}
 *
 * If the {feeTokenAddress} is this contract, use the internal ERC20 calls
 * to transfer the tokens directly. Otherwise, use the {SafeERC20TransferFrom} library
 * to transfer the tokens.
 */
function _handleFees(
    address feeTokenAddress,
    uint256 feeAmount
) internal virtual override returns (uint256) {
    if (feeAmount == 0) {
        return 0;
    }
    // If the {feeTokenAddress} is this contract, then just deposit the tokens directly.
    if (feeTokenAddress == address(this)) {
        _spendAllowance(_msgSender(), address(this), feeAmount);
        _transfer(_msgSender(), address(this), feeAmount);
        return feeAmount;
    }
    return
        SafeERC20TransferFrom.safeTransferFrom(IERC20(feeTokenAddress), _msgSender(), feeAmount);
}

Teleporterメッセージの手数料を処理するための内部関数。

親コントラクトの同名関数をオーバーライドしています。 feeAmountが0の場合は何もせず0を返します。 手数料として指定されたトークンがこのコントラクト自身(ラップされたネイティブトークン)の場合、_spendAllowanceと_transferを使ってユーザーからこのコントラクトへトークンを移動させます。 手数料トークンが外部のERC20トークンの場合、SafeERC20TransferFromライブラリを使って安全にユーザーからトークンをtransferFromします。

sequenceDiagram
    participant Caller as 親コントラクト (TokenRemote)
    participant Self as NativeTokenRemoteUpgradeable
    participant FeeToken as 外部Feeトークン
    
    Caller->>Self: _handleFees(feeTokenAddress, feeAmount)
    alt feeTokenAddress is this contract
        Self->>Self: _spendAllowance(...)
        Self->>Self: _transfer(...)
        Self-->>Caller: feeAmount を返す
    else feeTokenAddress is external
        Self->>FeeToken: safeTransferFrom(...)
        FeeToken-->>Self: 実際に確保した手数料額
        Self-->>Caller: 実際に確保した手数料額を返す
    end

引数

  • feeTokenAddress 手数料として使用するERC20トークンのアドレス。
  • feeAmount 手数料の額。

戻り値

  • uint256 実際に確保された手数料の額。

_mintNativeCoin

text
/**
 * @dev Mints coins to the recipient through the NativeMinter precompile.
 */
function _mintNativeCoin(address recipient, uint256 amount) private {
    NativeTokenRemoteStorage storage $ = _getNativeTokenRemoteStorage();
    $._totalMinted += amount;
    // Calls NativeMinter precompile through INativeMinter interface.
    NATIVE_MINTER.mintNativeCoin(recipient, amount);
}

NativeMinterプリコンパイルを通じてネイティブトークンをMint(発行)する内部関数。

このコントラクト内のネイティブトークンMint(発行)処理のコアとなるヘルパー関数です。 まず、Mint(発行)した総量を記録する_totalMinted変数を更新します。 次に、定数NATIVE_MINTERで定義されたプリコンパイルコントラクトのmintNativeCoin関数を呼び出し、指定されたrecipientにamount分のネイティブトークンを実際にMint(発行)させます。

sequenceDiagram
    participant Caller as 内部関数
    participant Self as NativeTokenRemoteUpgradeable
    participant NM as NativeMinter Precompile
    
    Caller->>Self: _mintNativeCoin(recipient, amount)
    Self->>Self: _totalMinted を加算
    Self->>NM: mintNativeCoin(recipient, amount)

引数

  • recipient ネイティブトークンを受け取るアドレス。
  • amount Mint(発行)するネイティブトークンの量。