# TokenRemote

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

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

## 概要

このコントラクトは、Avalanche Interchain Token Transfer (ICTT) のリモートチェーン側で機能する、アップグレード可能なコントラクトです。
特定の**TokenHome**コントラクトから送られてきたトークンを受け取り（Mint（発行）し）、そのトークンをBurnしてホームチェーン上の担保資産を償還したり、他のリモートコントラクトへ送付したりするための基盤ロジックを提供します。

**TokenRemote**コントラクトは、リモートチェーン側でトークンのMint（発行）とBurnを管理する役割を担います。
ホームチェーンの**TokenHome**コントラクトからクロスチェーンメッセージを受信すると、トークンをMint（発行）してユーザーに渡します。
逆に、ユーザーがこのコントラクトのトークンをホームチェーンに戻したり、別のリモートチェーンに送付したりする時は、トークンをBurnして**TokenHome**コントラクトへそのことを伝えるメッセージを送信します。

このコントラクトは抽象 (`abstract`) であるため、直接デプロイすることはできません。
アセットの具体的なMint（発行）（`_withdraw`）、Burn（`_burn`）、手数料処理（`_handleFees`）、`sendAndCall`メッセージを処理する方法（`_handleSendAndCall`）は、これを継承する**ERC20TokenRemote**や**NativeTokenRemote**といったコントラクトで実装される必要があります。

主な責務は以下の通りです。
* **ホームコントラクトとの連携**
    どの**TokenHome**コントラクトに紐づいているかを管理し、通信します。
* **登録**
    稼働を開始する前に自身を**TokenHome**コントラクトに登録する機能を提供します。
* **送付ロジック**
    シングルホップ（ホームに戻す）とマルチホップ（他リモートへ送る）の両方の送付ロジックを処理します。
* **小数桁数のスケーリング**
    ホームとリモートでトークンの小数桁数が異なる場合に対応するため、トークン量を自動的に換算します。
* **アップグレード可能性**
    　**ERC7201**規格のストレージレイアウトを採用し、安全なアップグレードを可能にしています。

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

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

## 機能

このコントラクトが提供する中核機能は以下です。

* **TokenHomeコントラクトへの登録**
    稼働開始時、自身の存在を**TokenHome**コントラクトに通知して登録します。
* **トークンの受信とMint（発行）**
    **TokenHome**コントラクトからのメッセージに基づき、トークンをMint（発行）するためのロジックを呼び出します。
* **トークンの送付（Burn）**
    ユーザーからの要求に基づきトークンをBurnし、シングルホップまたはマルチホップのメッセージを**TokenHome**コントラクトへ送信します。
* **送付とコントラクト呼び出し**
    トークンを送付すると同時に、送付先チェーンのスマートコントラクトを呼び出す機能の基盤を提供します。

## フロー

* TokenHomeコントラクトへの登録 (`registerWithHome`)
* トークンの送付（シングルホップ）
* トークンの受信 (`_receiveTeleporterMessage`)

### TokenHomeコントラクトへの登録 (`registerWithHome`)

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant TR as TokenRemote
    participant TP as Teleporter
    
    User->>TR: registerWithHome(feeInfo)
    TR->>TR: _handleFees(feeInfo) (抽象)
    TR->>TR: RegisterRemoteMessage を構築
    TR->>TP: _sendTeleporterMessage(...)
```

### トークンの送付（シングルホップ）

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant Child as 具象Remoteコントラクト
    participant TR as TokenRemote
    participant TP as Teleporter

    User->>Child: send(input, amount)
    Child->>TR: _send(input, amount)
    TR->>TR: _processSend(input, amount)
    TR->>TR: _prepareSend(...)
    TR->>Child: _burn(amount) (抽象)
    TR->>Child: _handleFees(...) (抽象)
    TR->>TR: SingleHopSendMessage を構築
    TR->>TP: _sendTeleporterMessage(...)
```

### トークンの受信 (`_receiveTeleporterMessage`)

```mermaid
sequenceDiagram
    participant TH as TokenHome
    participant TP as Teleporter
    participant TR as TokenRemote
    participant Child as 具象Remoteコントラクト
    
    TH->>TP: メッセージを送信
    TP->>TR: _receiveTeleporterMessage(...)
    TR->>TR: 送信元とメッセージタイプを検証
    TR->>TR: _isRegistered, _isCollateralized を true に更新
    TR->>Child: _withdraw(recipient, amount) (抽象)
```

## コード

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

## 構造体

### `TokenRemoteStorage`

```sol
struct TokenRemoteStorage {
    /// @notice The blockchain ID of the chain this contract is deployed on.
    bytes32 _blockchainID;
    /// @notice The blockchain ID of the TokenHome instance this contract receives tokens from.
    bytes32 _tokenHomeBlockchainID;
    /// @notice The address of the TokenHome instance this contract receives tokens from on the {tokenHomeBlockchainID}.
    address _tokenHomeAddress;
    /**
     * @notice The number of decimal places in the denomination of the home
     * token.
     * @dev Used to derive tokenMultiplier and multiplyOnRemote.
     */
    uint8 _homeTokenDecimals;
    /**
     * @notice The number of decimal places in the denomination of the remote token.
     * @dev Used to derive tokenMultiplier and multiplyOnRemote.
     */
    uint8 _tokenDecimals;
    /**
     * @notice tokenMultiplier allows this contract to scale the number of tokens it sends/receives to/from
     * its token TokenHome instance.
     *
     * @dev This is used to normalize the number of decimal places between the token home asset and the
     * token remote asset. It is derived from home and remote token decimals values passed in the constructor.
     */
    uint256 _tokenMultiplier;
    /**
     * @notice If {multiplyOnRemote} is true, the home token amount will be multiplied by {tokenMultiplier} when tokens
     * are transferred from the home into this remote, and divided by {tokenMultiplier} when tokens are transferred from
     * this remote back to its home.
     * If {multiplyOnRemote} is false, the home token amount value will be divided by {tokenMultiplier} when tokens
     * are transferred from the home into this remote, and multiplied by {tokenMultiplier} when tokens are transferred
     * from this remote back to its home.
     */
    bool _multiplyOnRemote;
    /**
     * @notice Initial reserve imbalance that the token for this TokenRemote instance starts with. The home contract must
     * collateralize a corresonding amount of home tokens before tokens can be minted on this contract.
     */
    uint256 _initialReserveImbalance;
    /**
     * @notice Whether or not the contract is known to be fully collateralized.
     */
    bool _isCollateralized;
    /**
     * @notice Whether or not the contract is known to be registered with its specified home contract.
     * This is set to true when the first message is received from the home contract. Note that {isRegistered}
     * will still be false after the remote contract is registered on the home contract until the first
     * message is received back from that contract.
     */
    bool _isRegistered;
}
```

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

- `_blockchainID`
    このコントラクトがデプロイされているブロックチェーンのID。
- `_tokenHomeBlockchainID`
    このコントラクトが連携する**TokenHome**コントラクトが存在するブロックチェーンのID。
- `_tokenHomeAddress`
    連携する**TokenHome**コントラクトのアドレス。
- `_homeTokenDecimals`
    ホームトークンの小数点の桁数。
- `_tokenDecimals`
    このリモートトークンの小数点の桁数。
- `_tokenMultiplier`
    ホームとリモートの小数桁数の差を補正するための乗数。
- `_multiplyOnRemote`
    トークン量換算の時、乗算と除算のどちらを適用するかを示すフラグ。
- `_initialReserveImbalance`
    このリモートチェーンの立ち上げ時に生成された、担保のない初期トークン供給量。
- `_isCollateralized`
    **TokenHome**コントラクト側で初期担保が満たされたことが確認できたかを示すフラグ。
- `_isRegistered`
    **TokenHome**コントラクトに登録され、最初のメッセージを受信したかを示すフラグ。

## 変数

### `TOKEN_REMOTE_STORAGE_LOCATION`

```sol
bytes32 public constant TOKEN_REMOTE_STORAGE_LOCATION =
    0x600d6a9b283d1eda563de594ce4843869b6f128a4baa222422ed94a60b0cef00;
```

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

### `MULTI_HOP_SEND_REQUIRED_GAS`

```sol
uint256 public constant MULTI_HOP_SEND_REQUIRED_GAS = 340_000;
```

マルチホップ送付メッセージを**TokenHome**コントラクトで処理するために必要な固定の推定ガス量。

### `MULTI_HOP_CALL_REQUIRED_GAS`

```sol
uint256 public constant MULTI_HOP_CALL_REQUIRED_GAS = 350_000;
```

マルチホップの「**送付とコントラクト呼び出し**」メッセージを**TokenHome**コントラクトで処理するために必要な固定の推定ガス量。

### `MULTI_HOP_CALL_GAS_PER_WORD`

```sol
uint256 public constant MULTI_HOP_CALL_GAS_PER_WORD = 1_500;
```

マルチホップの「**送付とコントラクト呼び出し**」メッセージにおいて、宛先ペイロードのデータ長（32バイトワード単位）ごとに追加で必要となるガス量。

### `REGISTER_REMOTE_REQUIRED_GAS`

```sol
uint256 public constant REGISTER_REMOTE_REQUIRED_GAS = 130_000;
```

このリモートコントラクトを**TokenHome**コントラクトに登録するために必要な固定の推定ガス量。

## 関数

### `_getTokenRemoteStorage`

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

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

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

**戻り値**

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

### `__TokenRemote_init`

```sol
// solhint-disable ordering
// solhint-disable-next-line func-name-mixedcase
function __TokenRemote_init(
    TokenRemoteSettings memory settings,
    uint256 initialReserveImbalance_,
    uint8 tokenDecimals
) internal onlyInitializing {
    __TeleporterRegistryOwnableApp_init(
        settings.teleporterRegistryAddress,
        settings.teleporterManager,
        settings.minTeleporterVersion
    );
    __SendReentrancyGuard_init();
    __TokenRemote_init_unchained(settings, initialReserveImbalance_, tokenDecimals);
}
```

アップグレード可能なコントラクトの初期設定を行う内部関数。

`initializer` Modifierを持つ公開関数から一度だけ呼び出されます。
まず、継承している`TeleporterRegistryOwnableAppUpgradeable`と`SendReentrancyGuardUpgradeable`の初期化関数をそれぞれ呼び出します。
その後、`__TokenRemote_init_unchained`を呼び出し、このコントラクトの変数を設定します。

```mermaid
sequenceDiagram
    participant Initializer as initialize()
    participant Self as TokenRemote
    participant Parent1 as Teleporter..App
    participant Parent2 as SendReentrancyGuard
    Initializer->>Self: __TokenRemote_init(...)
    Self->>Parent1: __Teleporter..._init()
    Self->>Parent2: __SendReentrancyGuard_init()
    Self->>Self: __TokenRemote_init_unchained(...)
```

**引数**

- `settings`
    `TokenRemoteSettings`構造体で、Teleporter関連のアドレスや連携する**TokenHome**コントラクトの情報を含みます。
- `initialReserveImbalance_`
    担保のない初期トークン供給量。
- `tokenDecimals`
    このリモートトークンの小数点の桁数。

### `__TokenRemote_init_unchained`

```sol
// solhint-disable-next-line func-name-mixedcase
function __TokenRemote_init_unchained(
    TokenRemoteSettings memory settings,
    uint256 initialReserveImbalance_,
    uint8 tokenDecimals
) internal onlyInitializing {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    $._blockchainID =
        IWarpMessenger(0x0200000000000000000000000000000000000005).getBlockchainID();
    require(
        settings.tokenHomeBlockchainID != bytes32(0),
        "TokenRemote: zero token home blockchain ID"
    );
    require(
        settings.tokenHomeBlockchainID != $._blockchainID,
        "TokenRemote: cannot deploy to same blockchain as token home"
    );
    require(settings.tokenHomeAddress != address(0), "TokenRemote: zero token home address");
    require(
        settings.tokenHomeDecimals <= TokenScalingUtils.MAX_TOKEN_DECIMALS,
        "TokenRemote: token home decimals too high"
    );
    require(
        tokenDecimals <= TokenScalingUtils.MAX_TOKEN_DECIMALS,
        "TokenRemote: token decimals too high"
    );
    $._tokenHomeBlockchainID = settings.tokenHomeBlockchainID;
    $._tokenHomeAddress = settings.tokenHomeAddress;
    $._initialReserveImbalance = initialReserveImbalance_;
    $._isCollateralized = initialReserveImbalance_ == 0;
    $._homeTokenDecimals = settings.tokenHomeDecimals;
    $._tokenDecimals = tokenDecimals;
    ($._tokenMultiplier, $._multiplyOnRemote) =
        TokenScalingUtils.deriveTokenMultiplierValues(settings.tokenHomeDecimals, tokenDecimals);
}
```

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

`onlyInitializing` Modifierで保護されています。
まず、Warp Messengerプリコンパイルから自身のチェーンIDを取得し、引数で渡された設定値の検証を行います。
その後、`TokenHome`のチェーンIDやアドレス、初期供給量などの変数をストレージに保存します。
最後に、`TokenScalingUtils.deriveTokenMultiplierValues`を呼び出して、小数桁数の差を補正するための乗数と計算方法を決定して保存します。

```mermaid
sequenceDiagram
    participant Init as __TokenRemote_init
    participant Self as TokenRemote
    participant Warp as Warp Messenger Precompile
    participant Utils as TokenScalingUtils
    Init->>Self: __TokenRemote_init_unchained(...)
    Self->>Self: 引数を検証 (require)
    Self->>Warp: getBlockchainID()
    Warp-->>Self: チェーンIDを返す
    Self->>Utils: deriveTokenMultiplierValues(...)
    Utils-->>Self: _tokenMultiplier, _multiplyOnRemote を返す
    Self->>Self: 全ての変数をストレージに保存
```

**引数**

- `settings`
    `TokenRemoteSettings`構造体。
- `initialReserveImbalance_`
    担保のない初期トークン供給量。
- `tokenDecimals`
    このリモートトークンの小数点の桁数。

### `registerWithHome`

```sol
/**
 * @notice Sends a message to the contract's specified token TokenHome instance to register this remote
 * instance. TokenRemote instances must be registered with their home contract prior to being able to receive
 * tokens from them.
 */
function registerWithHome(
    TeleporterFeeInfo calldata feeInfo
) external virtual {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    require(!$._isRegistered, "TokenRemote: already registered");

    // Send a message to the token TokenHome instance to register this TokenRemote instance.
    RegisterRemoteMessage memory registerMessage = RegisterRemoteMessage({
        initialReserveImbalance: $._initialReserveImbalance,
        homeTokenDecimals: $._homeTokenDecimals,
        remoteTokenDecimals: $._tokenDecimals
    });
    TransferrerMessage memory message = TransferrerMessage({
        messageType: TransferrerMessageType.REGISTER_REMOTE,
        payload: abi.encode(registerMessage)
    });

    uint256 feeAmount = _handleFees(feeInfo.feeTokenAddress, feeInfo.amount);
    _sendTeleporterMessage(
        TeleporterMessageInput({
            destinationBlockchainID: $._tokenHomeBlockchainID,
            destinationAddress: $._tokenHomeAddress,
            feeInfo: TeleporterFeeInfo({feeTokenAddress: feeInfo.feeTokenAddress, amount: feeAmount}),
            requiredGasLimit: REGISTER_REMOTE_REQUIRED_GAS,
            allowedRelayerAddresses: new address[](0),
            message: abi.encode(message)
        })
    );
}
```

このリモートコントラクトを、連携する**TokenHome**コントラクトに登録するための関数。

まだ登録されていないこと (`!_isRegistered`) を確認します。
次に、`RegisterRemoteMessage`を構築し、`TransferrerMessage`でラップします。
`_handleFees`を呼び出してメッセージ手数料を処理した後、`_sendTeleporterMessage`を呼び出して、**TokenHome**コントラクトへ登録メッセージを送信します。

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant Self as TokenRemote
    participant TP as Teleporter
    
    User->>Self: registerWithHome(feeInfo)
    Self->>Self: _isRegistered を検証
    Self->>Self: RegisterRemoteMessage を構築
    Self->>Self: _handleFees(feeInfo) (抽象)
    Self-->>Self: feeAmount を受け取る
    Self->>TP: _sendTeleporterMessage(...)
```

**引数**

- `feeInfo`
    Teleporterメッセージのrelayerに支払う手数料の情報。

### `calculateNumWords`

```sol
/**
 * @dev Calculates the number of 32-byte words required to fit a payload of a given length.
 * The payloads are padded to have a length that is a multiple of 32.
 */
function calculateNumWords(
    uint256 payloadSize
) public pure returns (uint256) {
    // Add 31 to effectively round up to the nearest multiple of 32.
    // Right-shift by 5 bits to divide by 32.
    return (payloadSize + 31) >> 5;
}
```

与えられたバイトサイズが、32バイトのワード単位でいくつになるかを計算する関数。

ペイロードのガス代を計算するために使用されるヘルパー関数です。
与えられた`payloadSize`を32で割った時の切り上げの整数を計算します。

**引数**

- `payloadSize`
    計算対象のペイロードのバイトサイズ。

**戻り値**

- `uint256`
    32バイトを1ワードとした時のワード数。

### `getIsCollateralized`

```sol
function getIsCollateralized() public view returns (bool) {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    return $._isCollateralized;
}
```

このコントラクトが完全に担保されているかどうかの状態を返す関数。

変数`_isCollateralized`の値を返します。
この値は、**TokenHome**コントラクトから最初のメッセージを受信した時に`true`になります。
連携しているTokenHomeコントラクトには、「**リモートが必要とする初期担保がすべて満たされるまで、そのリモートへのトークン送付メッセージを一切送信しない**」というルールがあります。
そのため、この**TokenRemote**コントラクトが**TokenHome**から最初のメッセージを受信したという事実は、その時点で初期担保が既に満たされていることの証明になります。
そのため、このコントラクトはメッセージを受信したタイミングで、自身の_isCollateralizedフラグを安全にtrueに更新することができます。

**戻り値**

- `bool`
    完全に担保されていれば`true`、そうでなければ`false`。

### `getTokenMultiplier`

```sol
function getTokenMultiplier() public view returns (uint256) {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    return $._tokenMultiplier;
}
```

ホームトークンとリモートトークン間の小数桁数補正に使う乗数を返す関数。

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

**戻り値**

- `uint256`
    トークン量の換算に使用される乗数。

### `getMultiplyOnRemote`

```sol
function getMultiplyOnRemote() public view returns (bool) {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    return $._multiplyOnRemote;
}
```

トークン量換算の計算方法を示すフラグを返す関数。

変数`_multiplyOnRemote`の値を返します。
このフラグが`true`か`false`かによって、`_tokenMultiplier`を乗算するか除算するかが決まります。

**戻り値**

- `bool`
    トークン量換算の計算方法を示すフラグ。

### `getTokenHomeBlockchainID`

```sol
function getTokenHomeBlockchainID() public view returns (bytes32) {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    return $._tokenHomeBlockchainID;
}
```

連携する**TokenHome**コントラクトが存在するブロックチェーンのIDを返す関数。

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

**戻り値**

- `bytes32`
    **TokenHome**コントラクトのチェーンID。

### `getTokenHomeAddress`

```sol
function getTokenHomeAddress() public view returns (address) {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    return $._tokenHomeAddress;
}
```

連携する**TokenHome**コントラクトのアドレスを返す関数。

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

**戻り値**

- `address`
    **TokenHome**コントラクトのアドレス。

### `getInitialReserveImbalance`

```sol
function getInitialReserveImbalance() public view returns (uint256) {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    return $._initialReserveImbalance;
}
```

担保のない初期トークン供給量を返す関数。

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

**戻り値**

- `uint256`
    担保のない初期トークン供給量。

### `getBlockchainID`

```sol
function getBlockchainID() public view returns (bytes32) {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    return $._blockchainID;
}
```

このコントラクトがデプロイされているブロックチェーンのIDを返す関数。

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

**戻り値**

- `bytes32`
    このコントラクトのチェーンID。

### `_send`

```sol
/**
 * @notice Sends tokens to the specified destination.
 *
 * @dev Burns the transferred amount, and uses Teleporter to send a cross chain message to the token TokenHome instance.
 * Tokens can be sent the token TokenHome instance, or to any TokenRemote instance registered with the home other than this one.
 */
function _send(SendTokensInput calldata input, uint256 amount) internal sendNonReentrant {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    _validateSendTokensInput(input);
    if (input.destinationBlockchainID == $._tokenHomeBlockchainID) {
        _processSend(input, amount);
    } else {
        _processSendMultiHop(input, amount);
    }
}
```

トークンを送付するための内部関数。

`sendNonReentrant` Modifierで保護されています。
入力値を検証した後、送付先が**TokenHome**コントラクトのチェーン（`_tokenHomeBlockchainID`）であれば、シングルホップ処理の`_processSend`を呼び出します。
そうでなければ、マルチホップ処理の`_processSendMultiHop`を呼び出します。

```mermaid
sequenceDiagram
    participant Caller as 継承先コントラクト
    participant Self as TokenRemote
    
    Caller->>Self: _send(input, amount)
    Self->>Self: _validateSendTokensInput(input)
    alt destination is TokenHome
        Self->>Self: _processSend(input, amount)
    else destination is another Remote
        Self->>Self: _processSendMultiHop(input, amount)
    end
```

**引数**

- `input`
    送付先情報などを含む`SendTokensInput`構造体。
- `amount`
    送付するトークンの量。

### `_sendAndCall`

```sol
/**
 * @notice Sends tokens to the specified recipient contract on the destination blockchain ID by
 * calling the {receiveTokens} method of the respective recipient.
 *
 * @dev Burns the transferred amount, and uses Teleporter to send a cross chain message.
 * Tokens and data can be sent to the token TokenHome instance, or to any TokenRemote instance registered with the home
 * other than this one.
 */
function _sendAndCall(
    SendAndCallInput calldata input,
    uint256 amount
) internal sendNonReentrant {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    _validateSendAndCallInput(input);

    if (input.destinationBlockchainID == $._tokenHomeBlockchainID) {
        return _processSendAndCall(input, amount);
    } else {
        return _processSendAndCallMultiHop(input, amount);
    }
}
```

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

`sendNonReentrant` Modifierで保護されています。
入力値を検証した後、送付先が**TokenHome**コントラクトのチェーンであれば、シングルホップ処理の`_processSendAndCall`を呼び出します。
そうでなければ、マルチホップ処理の`_processSendAndCallMultiHop`を呼び出します。

```mermaid
sequenceDiagram
    participant Caller as 継承先コントラクト
    participant Self as TokenRemote
    
    Caller->>Self: _sendAndCall(input, amount)
    Self->>Self: _validateSendAndCallInput(input)
    alt destination is TokenHome
        Self->>Self: _processSendAndCall(input, amount)
    else destination is another Remote
        Self->>Self: _processSendAndCallMultiHop(input, amount)
    end
```

**引数**

- `input`
    宛先コントラクト情報などを含む`SendAndCallInput`構造体。
- `amount`
    送付するトークンの量。


### `_receiveTeleporterMessage`

```sol
/**
 * @notice Handles receiving messages from the token TokenHome instance. The supported message types are
 * single-hop sends, and single-hop calls.
 *
 * @dev See {ITeleporterUpgradeable-_receiveTeleporterMessage}
 */
function _receiveTeleporterMessage(
    bytes32 sourceBlockchainID,
    address originSenderAddress,
    bytes memory message
) internal override {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    require(
        sourceBlockchainID == $._tokenHomeBlockchainID,
        "TokenRemote: invalid source blockchain ID"
    );
    require(
        originSenderAddress == $._tokenHomeAddress, "TokenRemote: invalid origin sender address"
    );
    TransferrerMessage memory transferrerMessage = abi.decode(message, (TransferrerMessage));

    // If the contract was not previously known to be registered or collateralized, it is now given that
    // the home has sent a message to mint funds.
    if (!$._isRegistered || !$._isCollateralized) {
        $._isRegistered = true;
        $._isCollateralized = true;
    }

    // Remote contracts should only ever receive single-hop messages because
    // multi-hop messages are always routed through the home contract.
    if (transferrerMessage.messageType == TransferrerMessageType.SINGLE_HOP_SEND) {
        SingleHopSendMessage memory payload =
            abi.decode(transferrerMessage.payload, (SingleHopSendMessage));
        _withdraw(payload.recipient, payload.amount);
    } else if (transferrerMessage.messageType == TransferrerMessageType.SINGLE_HOP_CALL) {
        // The {sourceBlockchainID}, and {originSenderAddress} specified in the message
        // payload will not match the sender of this Teleporter message in the case of a
        // multi-hop message. Since Teleporter messages are only received from the specified
        // token TokenHome instance, no additional authentication is needed on the payload values.
        SingleHopCallMessage memory payload =
            abi.decode(transferrerMessage.payload, (SingleHopCallMessage));
        _handleSendAndCall(payload, payload.amount);
    } else {
        revert("TokenRemote: invalid message type");
    }
}
```

**TokenHome**コントラクトからクロスチェーンメッセージを受信した時のメインハンドラー関数。

Teleporterから呼び出されるエントリーポイントです。
まず、メッセージが登録済みの**TokenHome**コントラクトから送られてきたことを検証します。
次に、`_isRegistered`と`_isCollateralized`フラグを`true`に更新します（このメッセージが届いたこと自体が、登録と担保の証明になるためです）。

メッセージのタイプを判別し、`SINGLE_HOP_SEND`であれば`_withdraw`（抽象関数）を、`SINGLE_HOP_CALL`であれば`_handleSendAndCall`（抽象関数）を呼び出して、これを継承する**ERC20TokenRemote**や**NativeTokenRemote**に実際のトークン処理を任せます。

```mermaid
sequenceDiagram
    participant TP as Teleporter
    participant Self as TokenRemote
    
    TP->>Self: _receiveTeleporterMessage(...)
    Self->>Self: 送信元がTokenHomeであることを検証
    Self->>Self: _isRegistered, _isCollateralized を true に更新
    Self->>Self: message をデコード
    alt messageType is SINGLE_HOP_SEND
        Self->>Self: _withdraw(recipient, amount) (抽象)
    else messageType is SINGLE_HOP_CALL
        Self->>Self: _handleSendAndCall(payload, amount) (抽象)
    else
        Self->>Self: revert
    end
```

**引数**

- `sourceBlockchainID`
    メッセージの送信元チェーンID。
- `originSenderAddress`
    メッセージの送信元アドレス（**TokenHome**コントラクトのアドレス）。
- `message`
    エンコードされた`TransferrerMessage`。

### `_withdraw`

```sol
/**
 * @notice Withdraws tokens to the recipient address.
 * @param recipient The address to withdraw tokens to
 * @param amount The amount of tokens to withdraw
 */
function _withdraw(address recipient, uint256 amount) internal virtual;
```

トークンをMint（発行）して受取人のアドレスに送付するための内部関数。

`_receiveTeleporterMessage`から呼び出されます。
この関数は具体的な実装を持たず、子コントラクトがアセットの種類に応じて、トークンをMint（発行）して指定された`recipient`に送付する処理を実装する必要があります。

**引数**

- `recipient`
    トークンを受け取るアドレス。
- `amount`
    Mint（発行）するトークンの量。

### `_burn`

```sol
/**
 * @notice Burns the user's tokens to initiate a token transfer.
 * @param amount The amount of tokens to burn
 * @return The amount of tokens burned, which is the amount to credit
 * for the token transfer.
 */
function _burn(
    uint256 amount
) internal virtual returns (uint256);
```

送付を開始するためにユーザーのトークンをBurnするための内部関数。

送付処理の最初に呼び出されます。
この関数は具体的な実装を持たず、子コントラクトがアセットの種類に応じて、ユーザーが保有するトークンをBurnする処理を実装する必要があります。

**引数**

- `amount`
    Burnするトークンの量。

**戻り値**

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

### `_handleSendAndCall`

```sol
/**
 * @notice Processes a send and call message by calling the recipient contract.
 * @param message The send and call message include recipient calldata
 * @param amount The amount of tokens to be sent to the recipient. This amount is assumed to be
 * already scaled to the local denomination of this contract.
 */
function _handleSendAndCall(
    SingleHopCallMessage memory message,
    uint256 amount
) internal virtual;
```

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

`_receiveTeleporterMessage`から呼び出されます。
この関数は具体的な実装を持たず、子コントラクトがアセットの種類に応じて、トークンをMint（発行）して指定された宛先コントラクトを呼び出す処理を実装する必要があります。

**引数**

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

### `_handleFees`

```sol
/**
 * @notice Handles fees sent to this contract for a token transfer.
 * The fee is expected to be approved by the sender for this token transfer contract to use,
 * and will be transferred to this contract to allocate for the token transfer.
 * @param feeTokenAddress The address of the fee token
 * @param feeAmount The amount of the fee
 */
function _handleFees(
    address feeTokenAddress,
    uint256 feeAmount
) internal virtual returns (uint256);
```

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

`registerWithHome`や`_prepareSend`などから呼び出されます。
この関数は具体的な実装を持たず、子コントラクトが手数料として指定された**ERC20**トークンをユーザーからこのコントラクトへ`transferFrom`する処理を実装する必要があります。

**引数**

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

**戻り値**

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

### `_prepareSend`

```sol
/**
 * @dev Prepares tokens to be sent to another chain by handling the
 * deposit, burning, and checking that the corresonding amount of
 * home tokens is greater than zero.
 */
function _prepareSend(
    uint256 amount,
    address primaryFeeTokenAddress,
    uint256 primaryFee,
    uint256 secondaryFee
) private returns (uint256, uint256) {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();

    // Burn the amount of tokens that will be transferred.
    amount = _burn(amount);

    // Transfer the primary fee to pay for fees on the first hop.
    // The user can specify this contract as {primaryFeeTokenAddress},
    // in which case the fee will be paid on top of the transferred amount.
    primaryFee = _handleFees(primaryFeeTokenAddress, primaryFee);

    // The transferred amount must cover the secondary fee, because the secondary fee
    // is directly subtracted from the transferred amount on the intermediate (home) chain
    // performing the multi-hop, before forwarding to the final destination TokenRemote instance.
    require(
        TokenScalingUtils.removeTokenScale($._tokenMultiplier, $._multiplyOnRemote, amount)
            > TokenScalingUtils.removeTokenScale(
                $._tokenMultiplier, $._multiplyOnRemote, secondaryFee
            ),
        "TokenRemote: insufficient tokens to transfer"
    );

    // Return the amount in this contract's local denomination and the primary fee.
    return (amount, primaryFee);
}
```

トークン送付の準備（Burnと手数料処理）を行う内部関数。

まず`_burn`（抽象関数）を呼び出してユーザーのトークンをBurnします。
次に`_handleFees`（抽象関数）を呼び出して、最初のホップの手数料をユーザーから確保します。
マルチホップの場合に備え、Burnしたトークン量が2番目のホップの手数料（`secondaryFee`）を上回っていることを、小数桁数をホームチェーン基準に換算した上で検証します。

```mermaid
sequenceDiagram
    participant Caller as _processSend...
    participant Self as TokenRemote
    
    Caller->>Self: _prepareSend(...)
    Self->>Self: _burn(amount) (抽象)
    Self-->>Self: 実際にBurnされたamountを受け取る
    Self->>Self: _handleFees(primaryFee) (抽象)
    Self-->>Self: 実際に確保したprimaryFeeを受け取る
    Self->>Self: amountがsecondaryFeeを上回るか検証
    Self-->>Caller: amount, primaryFee を返す
```

**引数**

- `amount`
    送付するトークン量。
- `primaryFeeTokenAddress`
    最初のホップの手数料トークンのアドレス。
- `primaryFee`
    最初のホップの手数料額。
- `secondaryFee`
    2番目のホップの手数料額。

**戻り値**

- `uint256`
    実際にBurnされたトークン量。
- `uint256`
    実際に確保された最初のホップの手数料額。

### `_processSend`

```sol
/**
 * @dev Sends tokens to the specified destination.
 */
function _processSend(SendTokensInput calldata input, uint256 amount) private {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    _validateSingleHopInput(
        input.destinationTokenTransferrerAddress, input.secondaryFee, input.multiHopFallback
    );

    uint256 primaryFee;
    (amount, primaryFee) = _prepareSend({
        amount: amount,
        primaryFeeTokenAddress: input.primaryFeeTokenAddress,
        primaryFee: input.primaryFee,
        secondaryFee: input.secondaryFee
    });

    TransferrerMessage memory message = TransferrerMessage({
        messageType: TransferrerMessageType.SINGLE_HOP_SEND,
        payload: abi.encode(SingleHopSendMessage({recipient: input.recipient, amount: amount}))
    });

    bytes32 messageID = _sendTeleporterMessage(
        TeleporterMessageInput({
            destinationBlockchainID: $._tokenHomeBlockchainID,
            destinationAddress: $._tokenHomeAddress,
            feeInfo: TeleporterFeeInfo({
                feeTokenAddress: input.primaryFeeTokenAddress,
                amount: primaryFee
            }),
            requiredGasLimit: input.requiredGasLimit,
            allowedRelayerAddresses: new address[](0),
            message: abi.encode(message)
        })
    );

    emit TokensSent(messageID, _msgSender(), input, amount);
}
```

シングルホップ（**TokenHome**へ戻す）のトークン送付処理を行う内部関数。

`_send`から呼び出されます。
まず`_validateSingleHopInput`で入力値を検証します。
`_prepareSend`でトークンのBurnと手数料処理を行った後、`SINGLE_HOP_SEND`タイプのメッセージを構築し、`_sendTeleporterMessage`で**TokenHome**コントラクトへ送信します。
最後に`TokensSent`イベントを発行します。

```mermaid
sequenceDiagram
    participant Caller as _send
    participant Self as TokenRemote
    participant TP as Teleporter
    
    Caller->>Self: _processSend(input, amount)
    Self->>Self: _validateSingleHopInput(input)
    Self->>Self: _prepareSend(...)
    Self-->>Self: amount, primaryFee を受け取る
    Self->>Self: SingleHopSendMessage を構築
    Self->>TP: _sendTeleporterMessage(...)
    TP-->>Self: messageID を返す
    Self->>Self: TokensSent イベントを発行
```

**引数**

- `input`
    送付先情報などを含む`SendTokensInput`構造体。
- `amount`
    送付するトークンの量。

### `_processSendMultiHop`

```sol
/**
 * @dev Sends tokens to the specified destination via multi-hop.
 */
function _processSendMultiHop(SendTokensInput calldata input, uint256 amount) private {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    _validateMultiHopInput(
        input.destinationBlockchainID,
        input.destinationTokenTransferrerAddress,
        input.multiHopFallback
    );

    uint256 primaryFee;
    (amount, primaryFee) = _prepareSend({
        amount: amount,
        primaryFeeTokenAddress: input.primaryFeeTokenAddress,
        primaryFee: input.primaryFee,
        secondaryFee: input.secondaryFee
    });

    TransferrerMessage memory message = TransferrerMessage({
        messageType: TransferrerMessageType.MULTI_HOP_SEND,
        payload: abi.encode(
            MultiHopSendMessage({
                destinationBlockchainID: input.destinationBlockchainID,
                destinationTokenTransferrerAddress: input.destinationTokenTransferrerAddress,
                recipient: input.recipient,
                amount: amount,
                secondaryFee: input.secondaryFee,
                secondaryGasLimit: input.requiredGasLimit,
                multiHopFallback: input.multiHopFallback
            })
        )
    });

    bytes32 messageID = _sendTeleporterMessage(
        TeleporterMessageInput({
            destinationBlockchainID: $._tokenHomeBlockchainID,
            destinationAddress: $._tokenHomeAddress,
            feeInfo: TeleporterFeeInfo({
                feeTokenAddress: input.primaryFeeTokenAddress,
                amount: primaryFee
            }),
            requiredGasLimit: MULTI_HOP_SEND_REQUIRED_GAS,
            allowedRelayerAddresses: new address[](0),
            message: abi.encode(message)
        })
    );

    emit TokensSent(messageID, _msgSender(), input, amount);
}
```

マルチホップ（他のリモートへ送る）のトークン送付処理を行う内部関数。

`_send`から呼び出されます。
`_validateMultiHopInput`で入力値を検証し、`_prepareSend`でトークンのBurnと手数料処理を行います。
その後、`MULTI_HOP_SEND`タイプのメッセージを構築し、**TokenHome**コントラクトへ送信します。
この時、ガスリミットには定数`MULTI_HOP_SEND_REQUIRED_GAS`が使用されます。
最後に`TokensSent`イベントを発行します。

```mermaid
sequenceDiagram
    participant Caller as _send
    participant Self as TokenRemote
    participant TP as Teleporter
    
    Caller->>Self: _processSendMultiHop(input, amount)
    Self->>Self: _validateMultiHopInput(...)
    Self->>Self: _prepareSend(...)
    Self-->>Self: amount, primaryFee を受け取る
    Self->>Self: MultiHopSendMessage を構築
    Self->>TP: _sendTeleporterMessage(...)
    TP-->>Self: messageID を返す
    Self->>Self: TokensSent イベントを発行
```

**引数**

- `input`
    送付先情報などを含む`SendTokensInput`構造体。
- `amount`
    送付するトークンの量。

### `_processSendAndCall`

```sol
/**
 * @dev Sends tokens to the specified recipient contract on the destination blockchain ID by
 * calling the {receiveTokens} method of the respective recipient.
 */
function _processSendAndCall(SendAndCallInput calldata input, uint256 amount) private {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    _validateSingleHopInput(
        input.destinationTokenTransferrerAddress, input.secondaryFee, input.multiHopFallback
    );

    uint256 primaryFee;
    (amount, primaryFee) = _prepareSend({
        amount: amount,
        primaryFeeTokenAddress: input.primaryFeeTokenAddress,
        primaryFee: input.primaryFee,
        secondaryFee: input.secondaryFee
    });

    TransferrerMessage memory message = TransferrerMessage({
        messageType: TransferrerMessageType.SINGLE_HOP_CALL,
        payload: abi.encode(
            SingleHopCallMessage({
                sourceBlockchainID: $._blockchainID,
                originTokenTransferrerAddress: address(this),
                originSenderAddress: _msgSender(),
                recipientContract: input.recipientContract,
                amount: amount,
                recipientPayload: input.recipientPayload,
                recipientGasLimit: input.recipientGasLimit,
                fallbackRecipient: input.fallbackRecipient
            })
        )
    });

    // Send message to the token TokenHome instance.
    bytes32 messageID = _sendTeleporterMessage(
        TeleporterMessageInput({
            destinationBlockchainID: $._tokenHomeBlockchainID,
            destinationAddress: $._tokenHomeAddress,
            feeInfo: TeleporterFeeInfo({
                feeTokenAddress: input.primaryFeeTokenAddress,
                amount: primaryFee
            }),
            requiredGasLimit: input.requiredGasLimit,
            allowedRelayerAddresses: new address[](0),
            message: abi.encode(message)
        })
    );

    emit TokensAndCallSent(messageID, _msgSender(), input, amount);
}
```

シングルホップの「**送付とコントラクト呼び出し**」処理を行う内部関数。

`_sendAndCall`から呼び出されます。
入力値検証、`_prepareSend`での準備は`_processSend`と同様です。
構築するメッセージが`SINGLE_HOP_CALL`タイプになり、送信元情報や宛先コントラクト情報など、より多くの情報を含みます。
メッセージ送信後、`TokensAndCallSent`イベントを発行します。

```mermaid
sequenceDiagram
    participant Caller as _sendAndCall
    participant Self as TokenRemote
    participant TP as Teleporter
    
    Caller->>Self: _processSendAndCall(input, amount)
    Self->>Self: _validateSingleHopInput(...)
    Self->>Self: _prepareSend(...)
    Self-->>Self: amount, primaryFee を受け取る
    Self->>Self: SingleHopCallMessage を構築
    Self->>TP: _sendTeleporterMessage(...)
    TP-->>Self: messageID を返す
    Self->>Self: TokensAndCallSent イベントを発行
```

**引数**

- `input`
    宛先コントラクト情報などを含む`SendAndCallInput`構造体。
- `amount`
    送付するトークンの量。

### `_processSendAndCallMultiHop`

```sol
/**
 * @dev Sends tokens to the specified recipient contract on the destination blockchain ID by
 * calling the {receiveTokens} method of the respective recipient.
 */
function _processSendAndCallMultiHop(SendAndCallInput calldata input, uint256 amount) private {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    _validateMultiHopInput(
        input.destinationBlockchainID,
        input.destinationTokenTransferrerAddress,
        input.multiHopFallback
    );

    uint256 primaryFee;
    (amount, primaryFee) = _prepareSend({
        amount: amount,
        primaryFeeTokenAddress: input.primaryFeeTokenAddress,
        primaryFee: input.primaryFee,
        secondaryFee: input.secondaryFee
    });

    TransferrerMessage memory message = TransferrerMessage({
        messageType: TransferrerMessageType.MULTI_HOP_CALL,
        payload: abi.encode(
            MultiHopCallMessage({
                originSenderAddress: _msgSender(),
                destinationBlockchainID: input.destinationBlockchainID,
                destinationTokenTransferrerAddress: input.destinationTokenTransferrerAddress,
                recipientContract: input.recipientContract,
                amount: amount,
                recipientPayload: input.recipientPayload,
                recipientGasLimit: input.recipientGasLimit,
                fallbackRecipient: input.fallbackRecipient,
                multiHopFallback: input.multiHopFallback,
                secondaryRequiredGasLimit: input.requiredGasLimit,
                secondaryFee: input.secondaryFee
            })
        )
    });

    // The required gas limit for the first message sent back to the TokenHome instance
    // needs to account for the number of words in the payload. Each word uses additional
    // gas to include in the message to the final destination chain.
    uint256 messageRequiredGasLimit = MULTI_HOP_CALL_REQUIRED_GAS
        + (calculateNumWords(input.recipientPayload.length) * MULTI_HOP_CALL_GAS_PER_WORD);

    // Send message to the token TokenHome instance
    bytes32 messageID = _sendTeleporterMessage(
        TeleporterMessageInput({
            destinationBlockchainID: $._tokenHomeBlockchainID,
            destinationAddress: $._tokenHomeAddress,
            feeInfo: TeleporterFeeInfo({
                feeTokenAddress: input.primaryFeeTokenAddress,
                amount: primaryFee
            }),
            requiredGasLimit: messageRequiredGasLimit,
            allowedRelayerAddresses: new address[](0),
            message: abi.encode(message)
        })
    );

    emit TokensAndCallSent(messageID, _msgSender(), input, amount);
}
```

マルチホップの「**送付とコントラクト呼び出し**」処理を行う内部関数。

`_sendAndCall`から呼び出されます。
`_validateMultiHopInput`と`_prepareSend`で準備した後、`MULTI_HOP_CALL`タイプのメッセージを構築します。
このメッセージは、最終的な宛先情報、ペイロード、手数料など、マルチホップに必要な全ての情報を含みます。
**TokenHome**へのメッセージ送信に必要なガスリミットは、ペイロードの長さに応じて動的に計算されます。
メッセージ送信後、`TokensAndCallSent`イベントを発行します。

```mermaid
sequenceDiagram
    participant Caller as _sendAndCall
    participant Self as TokenRemote
    participant TP as Teleporter
    
    Caller->>Self: _processSendAndCallMultiHop(input, amount)
    Self->>Self: _validateMultiHopInput(...)
    Self->>Self: _prepareSend(...)
    Self-->>Self: amount, primaryFee を受け取る
    Self->>Self: MultiHopCallMessage を構築
    Self->>Self: messageRequiredGasLimit を計算
    Self->>TP: _sendTeleporterMessage(...)
    TP-->>Self: messageID を返す
    Self->>Self: TokensAndCallSent イベントを発行
```

**引数**

- `input`
    宛先コントラクト情報などを含む`SendAndCallInput`構造体。
- `amount`
    送付するトークンの量。

### `_validateSingleHopInput`

```sol
function _validateSingleHopInput(
    address destinationTokenTransferrerAddress,
    uint256 secondaryFee,
    address multiHopFallback
) private view {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    require(
        destinationTokenTransferrerAddress == $._tokenHomeAddress,
        "TokenRemote: invalid destination token transferrer address"
    );
    require(secondaryFee == 0, "TokenRemote: non-zero secondary fee");
    require(multiHopFallback == address(0), "TokenRemote: non-zero multi-hop fallback");
}
```

シングルホップ送付の入力値を検証する内部関数。

シングルホップ送付（**TokenHome**へ戻す）に特化した検証を行います。
宛先アドレスが登録済みの`_tokenHomeAddress`と一致すること、`secondaryFee`が0であること、`multiHopFallback`がゼロアドレスであることを確認します。

**引数**

- `destinationTokenTransferrerAddress`
    宛先コントラクトアドレス。
- `secondaryFee`
    2番目のホップの手数料。
- `multiHopFallback`
    マルチホップ失敗時のフォールバックアドレス。

### `_validateMultiHopInput`

```sol
function _validateMultiHopInput(
    bytes32 destinationBlockchainID,
    address destinationTokenTransferrerAddress,
    address multiHopFallback
) private view {
    TokenRemoteStorage storage $ = _getTokenRemoteStorage();
    // If the destination blockchain ID is this blockchain, the destination
    // token transferrer address must be a different contract. This is a multi-hop case to
    // a different token transfer contract on this chain.
    if (destinationBlockchainID == $._blockchainID) {
        require(
            destinationTokenTransferrerAddress != address(this),
            "TokenRemote: invalid destination token transferrer address"
        );
    }
    require(multiHopFallback != address(0), "TokenRemote: zero multi-hop fallback");
}
```

マルチホップ送付の入力値を検証する内部関数。

マルチホップ送付に特化した検証を行います。
`multiHopFallback`がゼロアドレスでないことを確認します。
また、もし宛先が同じチェーン上である場合は、自分自身のアドレスでないことを確認します（自分から自分へのマルチホップは無効）。

**引数**

- `destinationBlockchainID`
    最終的な宛先のチェーンID。
- `destinationTokenTransferrerAddress`
    最終的な宛先コントラクトのアドレス。
- `multiHopFallback`
    マルチホップ失敗時のフォールバックアドレス。

### `_validateSendTokensInput`

```sol
function _validateSendTokensInput(
    SendTokensInput calldata input
) private pure {
    require(input.recipient != address(0), "TokenRemote: zero recipient address");
    require(input.requiredGasLimit > 0, "TokenRemote: zero required gas limit");
    require(
        input.destinationBlockchainID != bytes32(0),
        "TokenRemote: zero destination blockchain ID"
    );
    require(
        input.destinationTokenTransferrerAddress != address(0),
        "TokenRemote: zero destination token transferrer address"
    );
}
```

通常のトークン送付（`send`）を安全に実行するために入力値を検証する内部関数。

`send`関数が呼び出された時に、その引数である`SendTokensInput`構造体の内容が有効であるかを検証し、基本的な設定ミスによるトランザクションの失敗や資産の喪失を防ぎます。

- **宛先の検証**
    - `recipient`
        最終的なトークンの受取人アドレスがゼロでないことを確認します。
        ゼロアドレスへの送付はトークンの永久的な喪失を意味するため、これを防ぎます。
    - `destinationBlockchainID`
        宛先チェーンのIDがゼロでないことを確認します。
        これにより、メッセージが有効なブロックチェーンにルーティングされることが保証されます。
    - `destinationTokenTransferrerAddress`
        宛先チェーン上のトークンコントラクト（`TokenHome`または別の`TokenRemote`）のアドレスがゼロでないことを確認します。
        メッセージを処理する有効なコントラクトが存在することを保証します。

- **ガスリミットの検証**
    - `requiredGasLimit`
        宛先チェーンでTeleporterメッセージを実行するために必要なガスリミットが0より大きいことを確認します。
        ガスリミットが0の場合、トランザクションは宛先で確実に失敗するため、無駄な送付を防ぎます。

**引数**

- `input`
    検証対象の`SendTokensInput`構造体。

### `_validateSendAndCallInput`

```sol
function _validateSendAndCallInput(
    SendAndCallInput calldata input
) private pure {
    require(
        input.destinationBlockchainID != bytes32(0),
        "TokenRemote: zero destination blockchain ID"
    );
    require(
        input.destinationTokenTransferrerAddress != address(0),
        "TokenRemote: zero destination token transferrer address"
    );
    require(
        input.recipientContract != address(0), "TokenRemote: zero recipient contract address"
    );
    require(input.requiredGasLimit > 0, "TokenRemote: zero required gas limit");
    require(input.recipientGasLimit > 0, "TokenRemote: zero recipient gas limit");
    require(
        input.recipientGasLimit < input.requiredGasLimit,
        "TokenRemote: invalid recipient gas limit"
    );
    require(
        input.fallbackRecipient != address(0), "TokenRemote: zero fallback recipient address"
    );
}
```

「**送付とコントラクト呼び出し**」の入力値を検証する内部関数。

`sendAndCall`を安全に実行するための、入力値に対する一連の事前チェックを行います。

- **宛先の検証**
    - `destinationBlockchainID`
        宛先のチェーンIDがゼロでないことを確認します。
    - `destinationTokenTransferrerAddress`
        宛先チェーン上のトークンコントラクトのアドレスがゼロでないことを確認します。
    - `recipientContract`
        最終的に呼び出される宛先コントラクトのアドレスがゼロでないことを確認します。
    これらのチェックは、トークンが意図しない場所や無効なアドレスに送付されるのを防ぎます。

- **ガスリミットの検証**
    - `requiredGasLimit` > 0
        Teleporterメッセージ全体を処理するために必要なガスリミットが0より大きいことを確認します。
    - `recipientGasLimit` > 0
        最終的な宛先コントラクトを呼び出すためのガスリミットが0より大きいことを確認します。
    - `recipientGasLimit` < `requiredGasLimit`
        最も重要な検証の1つです。
        宛先コントラクト用のガス (`recipientGasLimit`) は、メッセージ全体用のガス (`requiredGasLimit`) よりも必ず小さくなければなりません。
        なぜなら、Teleporterのメッセンジャーコントラクト自体が、メッセージの受信、デコード、最終的な呼び出しの準備といった処理にガスを消費するためです。
        この条件を満たさない場合、トランザクションは確実に失敗します。

- **フォールバックの検証**
    - `fallbackRecipient`
        宛先コントラクトの呼び出しが失敗した場合に、送付されたトークンを受け取るためのフォールバックアドレスがゼロでないことを確認し、トークンの喪失を防ぎます。

**引数**

- `input`
    検証対象の`SendAndCallInput`構造体。
