# NativeTokenHomeUpgradeable

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

- URL: https://cardene.dev/books/avalanche-ictt/f73396
- 本: Avalanche ICTT (https://cardene.dev/books/avalanche-ictt.md)
- 章: 7 / 12
- 前の章: https://cardene.dev/books/avalanche-ictt/4871a6.md
- 次の章: https://cardene.dev/books/avalanche-ictt/973df0.md
- 公開日: 2025-09-19
- 更新日: 2025-09-19
- トピック: Blockchain
- タグ: ブロックチェーン, solidity, ethereum, smartcontract

## 概要

このコントラクトは、Avalanche Interchain Token Transfer (ICTT) のホームチェーン側で機能する、アップグレード可能なスマートコントラクトです。
このブロックチェーンのネイティブトークンを他のブロックチェーンへ送付するために、このコントラクトにロック（預け入れ）する役割を担います。

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

https://github.com/ava-labs/icm-contracts/blob/main/contracts/ictt/TokenHome/NativeTokenHome.sol

## 説明

**NativeTokenHomeUpgradeable**コントラクトは、**ERC20TokenHomeUpgradeable**のネイティブトークン版です。
ユーザーが他のチェーンへネイティブトークン（例: AVAX）を送りたい時、このコントラクトにネイティブトークンを送付します。
コントラクトは受け取ったネイティブトークンをロックし、リモートチェーン上の**TokenRemote**コントラクトに対してトークンをMint（発行）するよう指示するクロスチェーンメッセージを送信します。

ネイティブトークン自体はコントラクトではないため、このコントラクトは内部で**Wrapped Native Token**コントラクト（WAVAXなど）と連携して動作します。
ユーザーから預かったネイティブトークンはラップされ、**ERC20**トークンとして残高が管理されます。
トークンを引き出す時は、ラップされたトークンをアンラップしてネイティブトークンに戻し、ユーザーに送付します。

このコントラクトはアップグレード可能であるため、`constructor`の代わりに`initialize`関数で初期設定を行い、将来のロジック更新に対応しています。
また、**ERC7201**規格に準拠したストレージ管理により、アップグレード時の安全性も確保されています。

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

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

## 機能

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

* **ネイティブトークンの送付**
    ユーザーが指定したリモートチェーンへネイティブトークンを送付する機能。
* **ネイティブトークンの送付とコントラクト呼び出し**
    ネイティブトークンを送付すると同時に、送付先チェーンのスマートコントラクトの特定の関数を呼び出す機能。
* **担保の追加**
    リモートコントラクトの準備金として、追加でネイティブトークンを預け入れる機能。
* **ネイティブトークンの引き出し**
    リモートチェーンからトークンが返却された時に、ロックを解除してユーザーにネイティブトークンを返還する機能。

## フロー

* ネイティブトークンの送付 (`send`)
* ネイティブトークンの引き出し (`_withdraw`)
* 送付とコントラクト呼び出しの処理 (`_handleSendAndCall`)

### ネイティブトークンの送付 (`send`)

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant NTHU as NativeTokenHomeUpgradeable
    participant WNT as Wrapped Native Token
    participant TH as TokenHome (親)
    
    User->>NTHU: send(input) を呼び出し (msg.valueと共に)
    NTHU->>TH: _send(input, msg.value) を実行
    TH->>NTHU: _deposit(msg.value) を呼び出し
    NTHU->>WNT: deposit() を呼び出し (msg.valueと共に)
    WNT-->>NTHU: WNTをMint(発行)
    NTHU-->>TH: 預かった量を返す
    TH->>TH: クロスチェーンメッセージを構築・送信
```

### ネイティブトークンの引き出し (`_withdraw`)

```mermaid
sequenceDiagram
    participant TH as TokenHome (親)
    participant NTHU as NativeTokenHomeUpgradeable
    participant WNT as Wrapped Native Token
    participant Recipient as 受取人
    
    TH->>NTHU: _withdraw(recipient, amount) を呼び出し
    NTHU->>NTHU: TokensWithdrawn イベントを発行
    NTHU->>WNT: withdraw(amount) を呼び出し
    WNT->>NTHU: ネイティブトークンを送付 (receive()が処理)
    NTHU->>Recipient: ネイティブトークンを送付 (sendValue)
```

### 送付とコントラクト呼び出しの処理 (`_handleSendAndCall`)

```mermaid
sequenceDiagram
    participant TH as TokenHome (親)
    participant NTHU as NativeTokenHomeUpgradeable
    participant WNT as Wrapped Native Token
    participant RecipientContract as 宛先コントラクト
    participant Fallback as フォールバックアドレス

    TH->>NTHU: _handleSendAndCall(message, amount) を呼び出し
    NTHU->>WNT: withdraw(amount) を呼び出し
    WNT->>NTHU: ネイティブトークンを送付 (receive()が処理)
    NTHU->>NTHU: receiveTokens(...) のペイロードを構築
    NTHU->>RecipientContract: _callWithExactGasAndValue(gas, amount, payload)
    RecipientContract-->>NTHU: 成功/失敗 (success)
    alt success
        NTHU->>NTHU: CallSucceeded イベントを発行
    else
        NTHU->>NTHU: CallFailed イベントを発行
        NTHU->>Fallback: ネイティブトークンを送付 (sendValue)
    end
```

## コード

https://github.com/ava-labs/icm-contracts/blob/main/contracts/ictt/TokenHome/NativeTokenHomeUpgradeable.sol

## 構造体

### `NativeTokenHomeStorage`

```sol
struct NativeTokenHomeStorage {
    /**
     * @notice The wrapped native token contract that represents the native tokens on this chain.
     */
    IWrappedNativeToken _wrappedToken;
}
```

**ERC7201**に従い、アップグレード時のストレージ衝突を防ぐための名前空間ストレージ構造体。
このコントラクトが連携するWrapped Native Tokenコントラクトのアドレスを保持します。

- `_wrappedToken`
    このコントラクトがネイティブトークンをラップ/アンラップするために使用する`IWrappedNativeToken`インターフェース。

## 変数

### `NATIVE_TOKEN_HOME_STORAGE_LOCATION`

```sol
bytes32 public constant NATIVE_TOKEN_HOME_STORAGE_LOCATION =
    0x3b5030f10c94fcbdaa3022348ff0b82dbd4c0c71339e41ff59d0bdc92179d600;
```

`NativeTokenHomeStorage`構造体を格納するストレージスロットの位置を示す定数。
**ERC7201**規格で定められた計算式に基づいて算出された固定値で、この値を使ってインラインアセンブリで直接ストレージにアクセスします。

## 関数

### `_getNativeTokenHomeStorage`

```sol
// solhint-disable ordering
function _getNativeTokenHomeStorage() private pure returns (NativeTokenHomeStorage storage $) {
    // solhint-disable-next-line no-inline-assembly
    assembly {
        $.slot := NATIVE_TOKEN_HOME_STORAGE_LOCATION
    }
}
```

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

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

**戻り値**

- `NativeTokenHomeStorage storage $`
    `NativeTokenHomeStorage`構造体へのストレージポインタ。

### `constructor`

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

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

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

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

**引数**

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

### `initialize`

```sol
/**
 * @notice Initializes this token TokenHome instance to send native tokens to TokenRemote instances on other chains.
 * Always uses a {tokenDecimals} value of 18 since it is the denomination of the native token of EVM instances.
 * @param teleporterRegistryAddress The current blockchain ID's Teleporter registry
 * address. See here for details: https://github.com/ava-labs/icm-contracts/tree/main/contracts/teleporter/registry
 * @param teleporterManager Address that manages this contract's integration with the
 * Teleporter registry and Teleporter versions.
 * @param minTeleporterVersion Minimum Teleporter version supported by this contract.
 * @param wrappedTokenAddress The wrapped native token contract address of the native asset
 * to be transferred to TokenRemote instances.
 */
function initialize(
    address teleporterRegistryAddress,
    address teleporterManager,
    uint256 minTeleporterVersion,
    address wrappedTokenAddress
) public initializer {
    __NativeTokenHome_init(
        teleporterRegistryAddress, teleporterManager, minTeleporterVersion, wrappedTokenAddress
    );
}
```

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

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

```mermaid
sequenceDiagram
    participant Owner as オーナー
    participant Self as NativeTokenHomeUpgradeable
    
    Owner->>Self: initialize(...)
    Self->>Self: __NativeTokenHome_init(...)
```

**引数**

- `teleporterRegistryAddress`
    Teleporterレジストリコントラクトのアドレス。
- `teleporterManager`
    Teleporterメッセージを管理するTeleporterManagerのアドレス。
- `minTeleporterVersion`
    サポートするTeleporterの最低バージョン。
- `wrappedTokenAddress`
    連携するWrapped Native Tokenコントラクトのアドレス。

### `__NativeTokenHome_init`

```sol
// solhint-disable-next-line func-name-mixedcase
function __NativeTokenHome_init(
    address teleporterRegistryAddress,
    address teleporterManager,
    uint256 minTeleporterVersion,
    address wrappedTokenAddress
) internal onlyInitializing {
    __TokenHome_init(
        teleporterRegistryAddress,
        teleporterManager,
        minTeleporterVersion,
        wrappedTokenAddress,
        18
    );
    __NativeTokenHome_init_unchained(wrappedTokenAddress);
}
```

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

`onlyInitializing` Modifierにより、`initialize`関数からのみ呼び出せるように制限されています。まず親コントラクトの`__TokenHome_init`を呼び出します。その時、ネイティブトークンの小数桁数は常に18であるため、`tokenDecimals`には18をハードコードして渡します。
次に`__NativeTokenHome_init_unchained`を呼び出してこのコントラクトの変数を初期化します。

```mermaid
sequenceDiagram
    participant Caller as initialize()
    participant Self as NativeTokenHomeUpgradeable
    participant Parent as TokenHome
    
    Caller->>Self: __NativeTokenHome_init(...)
    Self->>Parent: __TokenHome_init(..., wrappedTokenAddress, 18)
    Self->>Self: __NativeTokenHome_init_unchained(...)
```

**引数**

- `teleporterRegistryAddress`
    Teleporterレジストリコントラクトのアドレス。
- `teleporterManager`
    Teleporterメッセージを管理するTeleporterManagerのアドレス。
- `minTeleporterVersion`
    サポートするTeleporterの最低バージョン。
- `wrappedTokenAddress`
    連携するWrapped Native Tokenコントラクトのアドレス。

### `__NativeTokenHome_init_unchained`

```sol
// solhint-disable-next-line func-name-mixedcase
function __NativeTokenHome_init_unchained(
    address wrappedTokenAddress
) internal onlyInitializing {
    _getNativeTokenHomeStorage()._wrappedToken = IWrappedNativeToken(wrappedTokenAddress);
}
```

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

`onlyInitializing` Modifierで保護されています。
`_getNativeTokenHomeStorage`を呼び出してストレージ構造体を取得し、連携対象となるWrapped Native Tokenコントラクトのアドレスを変数`_wrappedToken`に設定します。

```mermaid
sequenceDiagram
    participant Caller as __NativeTokenHome_init()
    participant Self as NativeTokenHomeUpgradeable
    
    Caller->>Self: __NativeTokenHome_init_unchained(wrappedTokenAddress)
    Self->>Self: _getNativeTokenHomeStorage()
    Self->>Self: _wrappedToken 変数に wrappedTokenAddress を保存
```

**引数**

- `wrappedTokenAddress`
    連携対象のWrapped Native Tokenコントラクトのアドレス。

### `receive`

```sol
/**
 * @notice Receives native tokens transferred to this contract.
 * @dev This function is called when the token transferrer is withdrawing native tokens to
 * transfer to the recipient. The caller must be the wrapped native token contract.
 */
receive() external payable {
    // The caller here is expected to be {tokenAddress} directly, and not through a meta-transaction,
    // so we check for `msg.sender` instead of `_msgSender()`.
    require(
        msg.sender == address(_getNativeTokenHomeStorage()._wrappedToken),
        "NativeTokenHome: invalid receive payable sender"
    );
}
```

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

この`receive`関数は、関数を指定せずに、このコントラクトアドレスへ直接ネイティブトークンが送付された時に実行されます。
このコントラクトでは、`_withdraw`関数内部でWrapped Native Tokenコントラクトの`withdraw`が呼び出され、その結果としてアンラップされたネイティブトークンがこのコントラクトに送り返されてくる、という特定の状況を想定しています。
そのため、送金元である`msg.sender`が、あらかじめ登録されたWrapped Native Tokenコントラクトのアドレスと一致することを検証し、意図しない入金を防いでいます。

### `send`

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

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

`payable`修飾子により、ネイティブトークンをトランザクションと共に受け取ることができます。
受け取ったネイティブトークンの量 (`msg.value`) を`amount`として、親コントラクトの`_send`関数を呼び出します。

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant Self as NativeTokenHomeUpgradeable
    participant Parent as TokenHome
    
    User->>Self: send(input) with msg.value
    Self->>Parent: _send(input, msg.value)
```

**引数**

- `input`
    送付先チェーンID、受取人アドレスなどを含む`SendTokensInput`構造体。

### `sendAndCall`

```sol
/**
 * @dev See {INativeTokenTransferrer-sendAndCall}
 */
function sendAndCall(
    SendAndCallInput calldata input
) external payable {
    _sendAndCall({
        sourceBlockchainID: getBlockchainID(),
        originTokenTransferrerAddress: address(this),
        originSenderAddress: _msgSender(),
        input: input,
        amount: msg.value
    });
}
```

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

`payable`修飾子でネイティブトークンを受け取ります。
引数を整形し、親コントラクト**TokenHome**に実装されている`_sendAndCall`関数を呼び出します。
送付額`amount`には`msg.value`が使用されます。

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant Self as NativeTokenHomeUpgradeable
    participant Parent as TokenHome
    
    User->>Self: sendAndCall(input) with msg.value
    Self->>Parent: _sendAndCall(...)
```

**引数**

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

### `addCollateral`

```sol
/**
 * @dev See {INativeTokenHome-addCollateral}
 */
function addCollateral(
    bytes32 remoteBlockchainID,
    address remoteTokenTransferrerAddress
) external payable {
    _addCollateral(remoteBlockchainID, remoteTokenTransferrerAddress, msg.value);
}
```

特定のリモートコントラクトの担保を追加するための関数。

`payable`修飾子でネイティブトークンを受け取ります。
受け取った量 (`msg.value`) を`amount`として、親コントラクトの`_addCollateral`関数を呼び出します。

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant Self as NativeTokenHomeUpgradeable
    participant Parent as TokenHome
    
    User->>Self: addCollateral(...) with msg.value
    Self->>Parent: _addCollateral(..., msg.value)
```

**引数**

- `remoteBlockchainID`
    担保を追加するリモートコントラクトが存在するチェーンのID。
- `remoteTokenTransferrerAddress`
    担保を追加するリモートコントラクトのアドレス。

### `_deposit`

```sol
/**
 * @dev See {TokenHome-_deposit}
 * Deposits the native tokens sent to this contract
 */
function _deposit(
    uint256 amount
) internal virtual override returns (uint256) {
    NativeTokenHomeStorage storage $ = _getNativeTokenHomeStorage();
    return SafeWrappedNativeTokenDeposit.safeDeposit($._wrappedToken, amount);
}
```

受け取ったネイティブトークンをWrapped Native Tokenにラップして預け入れる内部関数。

親コントラクト**TokenHome**の同名関数をオーバーライドしています。`SafeWrappedNativeTokenDeposit.safeDeposit`ライブラリを使用し、指定された`amount`のネイティブトークンを、登録されたWrapped Native Tokenコントラクトに安全に預け入れ（ラップし）ます。

```mermaid
sequenceDiagram
    participant Caller as 親コントラクト (TokenHome)
    participant Self as NativeTokenHomeUpgradeable
    participant WNT as Wrapped Native Token
    
    Caller->>Self: _deposit(amount)
    Self->>Self: _getNativeTokenHomeStorage()
    Self->>WNT: safeDeposit(amount)
    WNT-->>Self: 実際に預け入れた量
    Self-->>Caller: 実際に預け入れた量を返す
```

**引数**

- `amount`
    預け入れるネイティブトークンの量。

**戻り値**

- `uint256`
    実際にラップされたトークンの量。

### `_withdraw`

```sol
/**
 * @dev See {TokenHome-_withdraw}
 * Withdraws the wrapped tokens for native tokens,
 * and sends them to the recipient.
 */
function _withdraw(address recipient, uint256 amount) internal virtual override {
    NativeTokenHomeStorage storage $ = _getNativeTokenHomeStorage();
    emit TokensWithdrawn(recipient, amount);
    $._wrappedToken.withdraw(amount);
    payable(recipient).sendValue(amount);
}
```

ロックされていたネイティブトークンを受取人に返還するための内部関数。

親コントラクト**TokenHome**の同名関数をオーバーライドしています。
まず`TokensWithdrawn`イベントを発行します。
次に、Wrapped Native Tokenコントラクトの`withdraw`関数を呼び出して、`amount`分のトークンをアンラップします。
この時、アンラップされたネイティブトークンは`receive`関数経由でこのコントラクトに送られます。
最後に、`sendValue`を使って、アンラップされたネイティブトークンを指定された`recipient`に送金します。

```mermaid
sequenceDiagram
    participant Caller as 親コントラクト (TokenHome)
    participant Self as NativeTokenHomeUpgradeable
    participant WNT as Wrapped Native Token
    participant Recipient as 受取人
    
    Caller->>Self: _withdraw(recipient, amount)
    Self->>Self: TokensWithdrawn イベントを発行
    Self->>WNT: withdraw(amount)
    WNT->>Self: ネイティブトークンを送付 (receive()が処理)
    Self->>Recipient: sendValue(amount)
```

**引数**

- `recipient`
    ネイティブトークンを受け取るアドレス。
- `amount`
    引き出すネイティブトークンの量。

### `_handleSendAndCall`

```sol
/**
 * @dev See {TokenHome-_handleSendAndCall}
 *
 * Send the native tokens to the recipient contract as a part of the call to
 * {INativeSendAndCallReceiver-receiveTokens} on the recipient contract.
 * If the call fails or doesn't spend all of the tokens, the remaining amount is
 * sent to the fallback recipient.
 */
function _handleSendAndCall(
    SingleHopCallMessage memory message,
    uint256 amount
) internal virtual override {
    NativeTokenHomeStorage storage $ = _getNativeTokenHomeStorage();
    // Withdraw the native token from the wrapped native token contract.
    $._wrappedToken.withdraw(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);
    }
}
```

リモートチェーンから送られてきた`sendAndCall`メッセージを処理する内部関数。

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

```mermaid
sequenceDiagram
    participant Caller as 親コントラクト (TokenHome)
    participant Self as NativeTokenHomeUpgradeable
    participant WNT as Wrapped Native Token
    participant Recipient as 宛先コントラクト
    participant Fallback as フォールバックアドレス
    
    Caller->>Self: _handleSendAndCall(message, amount)
    Self->>WNT: withdraw(amount)
    WNT->>Self: ネイティブトークンを送付 (receive()が処理)
    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`
    送付されてきたネイティブトークンの量。
