# NativeTokenRemoteUpgradeable

> このコントラクトは、Avalanche Interchain Token Transfer (ICTT) の「リモートチェーン」側で機能する、アップグレード可能なスマートコントラクトです。

- URL: https://cardene.dev/books/avalanche-ictt/28f87d
- 本: Avalanche ICTT (https://cardene.dev/books/avalanche-ictt.md)
- 章: 10 / 12
- 前の章: https://cardene.dev/books/avalanche-ictt/33d3b7.md
- 次の章: https://cardene.dev/books/avalanche-ictt/handson.md
- 公開日: 2025-09-19
- 更新日: 2025-09-19
- トピック: Blockchain
- タグ: ブロックチェーン, solidity, ethereum, smartcontract

## 概要

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

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

https://github.com/ava-labs/icm-contracts/blob/main/contracts/ictt/TokenRemote/NativeTokenRemote.sol

**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`)

```mermaid
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）

```mermaid
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`)

```mermaid
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`)

```mermaid
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`)

```mermaid
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)
```

## コード

https://github.com/ava-labs/icm-contracts/blob/main/contracts/ictt/TokenRemote/NativeTokenRemoteUpgradeable.sol

## 構造体

### `NativeTokenRemoteStorage`

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

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

https://qiita.com/cardene/items/64ef137f8bd096681713

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

## 変数

### `NATIVE_TOKEN_REMOTE_STORAGE_LOCATION`

```sol
bytes32 public constant NATIVE_TOKEN_REMOTE_STORAGE_LOCATION =
    0x69a5f7616543528c4fbe43f410b1034bd6da4ba06c25bedf04617268014cf500;
```

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

### `BURNED_TX_FEES_ADDRESS`

```sol
address public constant BURNED_TX_FEES_ADDRESS = 0x0100000000000000000000000000000000000000;
```

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

### `BURNED_FOR_TRANSFER_ADDRESS`

```sol
address public constant BURNED_FOR_TRANSFER_ADDRESS = 0x0100000000000000000000000000000000010203;
```

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

### `HOME_CHAIN_BURN_ADDRESS`

```sol
address public constant HOME_CHAIN_BURN_ADDRESS = 0x0100000000000000000000000000000000010203;
```

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

### `NATIVE_MINTER`

```sol
INativeMinter public constant NATIVE_MINTER =
    INativeMinter(0x0200000000000000000000000000000000000001);
```

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

## イベント

### `ReportBurnedTxFees`

```sol
event ReportBurnedTxFees(bytes32 indexed teleporterMessageID, uint256 feesBurned);
```

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

## Modifier

### `onlyWhenCollateralized`

```sol
/**
 * @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`

```sol
// 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`

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

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

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

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

**引数**

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

### `initialize`

```sol
/**
 * @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`を呼び出し、コントラクトの初期設定をすべて行います。

```mermaid
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`

```sol
// 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`を呼び出してこのコントラクトの変数を初期化します。

```mermaid
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`

```sol
// 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`変数を設定します。

```mermaid
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`

```sol
/**
 * @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`

```sol
/**
 * @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`

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

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

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

```mermaid
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`

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

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

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

```mermaid
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`

```sol
/**
 * @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`イベントを発行します。

```mermaid
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`

```sol
/**
 * @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`を使って関数実行者に送金します。

```mermaid
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`

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

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

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

```mermaid
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`

```sol
/**
 * @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`がラップされたトークンの供給量を返すのとは対照的に、この関数はチェーン全体のネイティブトークン供給量を返します。

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

**戻り値**

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

### `getTotalMinted`

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

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

変数`_totalMinted`の値を返します。

**戻り値**

- `uint256`
    Mint（発行）されたネイティブトークンの総量。

### `_withdraw`

```sol
/**
 * @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（発行）します。

```mermaid
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`

```sol
/**
 * @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として扱います。

```mermaid
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`

```sol
/**
 * @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`イベントを発行し、ネイティブトークンをフォールバックアドレスに送金します。

```mermaid
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`

```sol
/**
 * @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`します。

```mermaid
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`

```sol
/**
 * @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（発行）させます。

```mermaid
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（発行）するネイティブトークンの量。
