# ERC20TokenHomeUpgradeable

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

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

## 概要

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

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

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

## 説明

**ERC20TokenHomeUpgradeable**コントラクトは、ICTTフレームワークのコアをなすコンポーネントです。
ユーザーが他のチェーン（リモートチェーン）へ**ERC20**トークンを送りたい時、まずこのホームチェーン上のコントラクトにトークンを預け入れます。
すると、このコントラクトがトークンをロックし、リモートチェーン上の**TokenRemote**コントラクトに対してトークンをMint（発行）するよう指示するクロスチェーンメッセージが送信されます。

このコントラクトはアップグレード可能に設計されているため、`constructor`の代わりに`initialize`関数で初期設定を行います。
これにより、将来コントラクトのロジックを更新しても、ロックされているトークンの残高などの状態は維持されます。
また、**ERC7201**規格に準拠した名前空間ストレージ（Namespace Storage）を採用しており、アップグレード時のストレージ衝突（変数の上書き）を防ぐ設計になっています。

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

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

実際のトークンの送受信や管理ロジックの多くは、親コントラクトである**TokenHome**から継承しており、このコントラクトは**ERC20**トークンに特化した処理（`transferFrom`や`transfer`の呼び出し）を実装しています。

## 機能

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

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

## フロー

* **ERC20**トークンの送付 (`send`)
* **ERC20**トークンの送付とコントラクト呼び出し (`sendAndCall`)

### ERC20トークンの送付 (`send`)

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant E20THU as ERC20TokenHomeUpgradeable
    participant ERC20 as ERC20トークンコントラクト
    participant TH as TokenHome (親コントラクト)

    User->>E20THU: send(input, amount) を呼び出し
    E20THU->>TH: _send(input, amount) を呼び出し
    TH->>E20THU: _deposit(amount) を呼び出し (overrideされた関数)
    E20THU->>ERC20: transferFrom(User, this, amount) を実行
    ERC20-->>E20THU: トークン転送
    E20THU-->>TH: 転送完了
    TH->>TH: クロスチェーンメッセージを構築・送信
```

### ERC20トークンの送付とコントラクト呼び出し (`sendAndCall`)

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant E20THU as ERC20TokenHomeUpgradeable
    participant TH as TokenHome (親コントラクト)
    participant DestContract as 宛先コントラクト (リモート)
    
    User->>E20THU: sendAndCall(input, amount) を呼び出し
    E20THU->>TH: _sendAndCall(...) を呼び出し
    note over TH: クロスチェーンメッセージがリモートチェーンに届き、<br/>リモートのTokenRemoteがE20THUの_handleSendAndCallを呼び出す、という流れを抽象化
    E20THU->>E20THU: _handleSendAndCall(message, amount) を実行
    E20THU->>E20THU: 宛先コントラクトへのAllowanceを増やす
    E20THU->>DestContract: receiveTokens(...) を呼び出し
    DestContract->>DestContract: 内部ロジックを実行
    DestContract-->>E20THU: 処理完了
    E20THU->>E20THU: Allowanceをリセット
    E20THU->>User: (もしあれば)未使用トークンをフォールバック宛先に送付
```

## コード

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

## 構造体

### `ERC20TokenHomeStorage`

```sol
struct ERC20TokenHomeStorage {
    /// @notice The ERC20 token this home contract transfers to TokenRemote instances.
    IERC20 _token;
}
```

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

- `_token`
    このホームコントラクトが送付対象として管理する**ERC20**トークンのインターフェース。

## 変数

### `ERC20_TOKEN_HOME_STORAGE_LOCATION`

```sol
bytes32 public constant ERC20_TOKEN_HOME_STORAGE_LOCATION =
    0x914a9547f6c3ddce1d5efbd9e687708f0d1d408ce129e8e1a88bce4f40e29500;
```

`ERC20TokenHomeStorage`構造体を格納するストレージスロットの位置を示す定数。
**ERC7201**規格で定められた計算式（`keccak256("avalanche-ictt.storage.ERC20TokenHome")`などを含む）に基づいて算出された固定値で、この値を使ってインラインアセンブリで直接ストレージにアクセスします。

## 関数

### `_getERC20TokenHomeStorage`

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

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

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

**戻り値**

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

### `constructor`

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

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

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

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

**引数**

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

### `initialize`

```sol
/**
 * @notice Initializes the token TokenHome instance to send ERC20 tokens to TokenRemote instances on other chains.
 * @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 tokenAddress The ERC20 token contract address to be transferred by the home.
 * @param tokenDecimals The number of decimals for the ERC20 token
 */
function initialize(
    address teleporterRegistryAddress,
    address teleporterManager,
    uint256 minTeleporterVersion,
    address tokenAddress,
    uint8 tokenDecimals
) public initializer {
    __ERC20TokenHome_init(
        teleporterRegistryAddress,
        teleporterManager,
        minTeleporterVersion,
        tokenAddress,
        tokenDecimals
    );
}
```

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

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

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

**引数**

- `teleporterRegistryAddress`
    Teleporterレジストリコントラクトのアドレス。
- `teleporterManager`
    Teleporterメッセージを管理するTeleporterManagerのアドレス。
- `minTeleporterVersion`
    サポートするTeleporterの最低バージョン。
- `tokenAddress`
    このホームコントラクトで管理するERC20トークンのアドレス。
- `tokenDecimals`
    管理対象となる**ERC20**トークンの小数点の桁数。

### `__ERC20TokenHome_init`

```sol
// solhint-disable-next-line func-name-mixedcase
function __ERC20TokenHome_init(
    address teleporterRegistryAddress,
    address teleporterManager,
    uint256 minTeleporterVersion,
    address tokenAddress,
    uint8 tokenDecimals
) internal onlyInitializing {
    __TokenHome_init(
        teleporterRegistryAddress,
        teleporterManager,
        minTeleporterVersion,
        tokenAddress,
        tokenDecimals
    );
    __ERC20TokenHome_init_unchained(tokenAddress);
}
```

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

`onlyInitializing` Modifierにより、`initialize`関数からのみ呼び出せるように制限されています。
まず`__TokenHome_init`を呼び出して親コントラクトの初期化を行い、次に`__ERC20TokenHome_init_unchained`を呼び出してこのコントラクトの初期化（トークンアドレスの設定）を行います。

```mermaid
sequenceDiagram
    participant Caller as initialize()
    participant Self as ERC20TokenHomeUpgradeable
    participant Parent as TokenHome
    
    Caller->>Self: __ERC20TokenHome_init(...)
    Self->>Parent: __TokenHome_init(...)
    Self->>Self: __ERC20TokenHome_init_unchained(...)
```

**引数**

- `teleporterRegistryAddress`
    Teleporterレジストリコントラクトのアドレス。
- `teleporterManager`
    Teleporterメッセージを管理するTeleporterManagerのアドレス。
- `minTeleporterVersion`
    サポートするTeleporterの最低バージョン。
- `tokenAddress`
    このホームコントラクトで管理する**ERC20**トークンのアドレス。
- `tokenDecimals`
    管理対象となる**ERC20**トークンの小数点の桁数。

### `__ERC20TokenHome_init_unchained`

```sol
// solhint-disable-next-line func-name-mixedcase
function __ERC20TokenHome_init_unchained(
    address tokenAddress
) internal onlyInitializing {
    _getERC20TokenHomeStorage()._token = IERC20(tokenAddress);
}
```

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

`onlyInitializing` Modifierで保護されています。
`_getERC20TokenHomeStorage`を呼び出してストレージ構造体を取得し、管理対象となる**ERC20**トークンのアドレスを状態変数`_token`に設定します。

```mermaid
sequenceDiagram
    participant Caller as __ERC20TokenHome_init()
    participant Self as ERC20TokenHomeUpgradeable
    
    Caller->>Self: __ERC20TokenHome_init_unchained(tokenAddress)
    Self->>Self: _getERC20TokenHomeStorage()
    Self->>Self: _token 変数に tokenAddress を保存
```

**引数**

- `tokenAddress`
    管理対象の**ERC20**トークンアドレス。

### `send`

```sol
/**
 * @dev See {IERC20TokenTransferrer-send}
 */
function send(SendTokensInput calldata input, uint256 amount) external {
    _send(input, amount);
}
```

リモートチェーンに**ERC20**トークンを送付するための関数。

受け取った引数をそのまま、親コントラクト**TokenHome**に実装されている内部関数`_send`に渡します。
`_send`関数内でトークンのロック（`_deposit`の呼び出し）とクロスチェーンメッセージの送信が行われます。

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant Self as ERC20TokenHomeUpgradeable
    participant Parent as TokenHome
    
    User->>Self: send(input, amount)
    Self->>Parent: _send(input, amount)
```

**引数**

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

### `sendAndCall`

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

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

引数を整形し、親コントラクト**TokenHome**に実装されている`_sendAndCall`関数を呼び出します。

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant Self as ERC20TokenHomeUpgradeable
    participant Parent as TokenHome
    
    User->>Self: sendAndCall(input, amount)
    Self->>Parent: _sendAndCall(...)
```

**引数**

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

### `addCollateral`

```sol
/**
 * @dev See {IERC20TokenHome-addCollateral}
 */
function addCollateral(
    bytes32 remoteBlockchainID,
    address remoteTokenTransferrerAddress,
    uint256 amount
) external {
    _addCollateral(remoteBlockchainID, remoteTokenTransferrerAddress, amount);
}
```

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

親コントラクト**TokenHome**に実装されている内部関数`_addCollateral`に処理を委譲します。

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant Self as ERC20TokenHomeUpgradeable
    participant Parent as TokenHome
    
    User->>Self: addCollateral(...)
    Self->>Parent: _addCollateral(...)
```

**引数**

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

### `_deposit`

```sol
/**
 * @dev See {TokenHome-_deposit}
 */
function _deposit(
    uint256 amount
) internal virtual override returns (uint256) {
    ERC20TokenHomeStorage storage $ = _getERC20TokenHomeStorage();
    return SafeERC20TransferFrom.safeTransferFrom($._token, _msgSender(), amount);
}
```

ユーザーから**ERC20**トークンを預かり、コントラクト内にロックするための内部関数。

親コントラクト**TokenHome**の同名関数をオーバーライドしています。
`SafeERC20TransferFrom.safeTransferFrom`ライブラリを使用し、関数実行者（`_msgSender()`）からこのコントラクトへ、指定された`amount`の**ERC20**トークンを安全に送付します。
ユーザーがこのコントラクトに対して事前に`approve`していることが前提となります。

```mermaid
sequenceDiagram
    participant Caller as 親コントラクト (TokenHome)
    participant Self as ERC20TokenHomeUpgradeable
    participant Token as ERC20 Token
    
    Caller->>Self: _deposit(amount)
    Self->>Self: _getERC20TokenHomeStorage()
    Self->>Token: safeTransferFrom(_msgSender(), this, amount)
    Token-->>Self: 実際に転送された量
    Self-->>Caller: 実際に転送された量を返す
```

**引数**

- `amount`
    預け入れるトークンの量。

**戻り値**

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

### `_withdraw`

```sol
/**
 * @dev See {TokenHome-_withdraw}
 */
function _withdraw(address recipient, uint256 amount) internal virtual override {
    ERC20TokenHomeStorage storage $ = _getERC20TokenHomeStorage();
    emit TokensWithdrawn(recipient, amount);
    $._token.safeTransfer(recipient, amount);
}
```

ロックされていた**ERC20**トークンを受取人に返還するための内部関数。

親コントラクト**TokenHome**の同名関数をオーバーライドしています。
リモートチェーンからトークンが返還された時に、Teleporter経由で呼び出されます。
`TokensWithdrawn`イベントを発行し、`safeTransfer`ライブラリを使って、ロックされていたトークンを指定された`recipient`に安全に送金します。

```mermaid
sequenceDiagram
    participant Caller as 親コントラクト (TokenHome)
    participant Self as ERC20TokenHomeUpgradeable
    participant Token as ERC20 Token
    
    Caller->>Self: _withdraw(recipient, amount)
    Self->>Self: _getERC20TokenHomeStorage()
    Self->>Self: TokensWithdrawn イベントを発行
    Self->>Token: safeTransfer(recipient, amount)
```

**引数**

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

### `_handleSendAndCall`

```sol
/**
 * @dev See {TokenHome-_handleSendAndCall}
 *
 * Approves the recipient contract to spend the amount of tokens from this contract,
 * and calls {IERC20SendAndCallReceiver-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 {
    ERC20TokenHomeStorage storage $ = _getERC20TokenHomeStorage();
    IERC20 token = $._token;
    // Approve the recipient contract to spend the amount from the collateral.
    SafeERC20.safeIncreaseAllowance($._token, message.recipientContract, amount);

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

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

    uint256 remainingAllowance = token.allowance(address(this), message.recipientContract);

    // Reset the recipient contract allowance to 0.
    SafeERC20.forceApprove(token, message.recipientContract, 0);

    if (success) {
        emit CallSucceeded(message.recipientContract, amount);
    } else {
        emit CallFailed(message.recipientContract, amount);
    }

    // Transfer any remaining allowance to the fallback recipient. This will be the
    // full amount if the call failed.
    if (remainingAllowance > 0) {
        token.safeTransfer(message.fallbackRecipient, remainingAllowance);
    }
}
```

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

この関数は、`sendAndCall`によって送られてきたトークンを使って、指定された宛先コントラクトを呼び出すロジックを担います。
まず、`safeIncreaseAllowance`を使い、このコントラクトが保有するトークンを宛先コントラクトが`amount`分だけ使用できるように承認（approve）します。
次に、`abi.encodeCall`で宛先コントラクトの`receiveTokens`関数を呼び出すためのペイロードを構築し、`_callWithExactGas`で外部呼び出しを実行します。
呼び出しの成否にかかわらず、`forceApprove`で`allowance`を0にリセットします。
呼び出しが成功したか失敗したかに応じてイベントを発行します。
最後に、宛先コントラクトが使用しなかったトークン（`allowance`の残り）があれば、それをフォールバック用の受取人アドレスに送金します。
呼び出しが失敗した時は、全額がフォールバック宛先に送られます。

```mermaid
sequenceDiagram
    participant Caller as 親コントラクト (TokenHome)
    participant Self as ERC20TokenHomeUpgradeable
    participant Token as ERC20 Token
    participant Recipient as 宛先コントラクト
    participant Fallback as フォールバックアドレス
    
    Caller->>Self: _handleSendAndCall(message, amount)
    Self->>Token: safeIncreaseAllowance(Recipient, amount)
    Self->>Self: receiveTokens(...) のペイロードを構築
    Self->>Recipient: _callWithExactGas(gasLimit, payload)
    Recipient-->>Self: 成功/失敗 (success)
    Self->>Token: allowance(this, Recipient)
    Token-->>Self: remainingAllowance
    Self->>Token: forceApprove(Recipient, 0)
    alt success
        Self->>Self: CallSucceeded イベントを発行
    else
        Self->>Self: CallFailed イベントを発行
    end
    
    opt remainingAllowance > 0
        Self->>Token: safeTransfer(Fallback, remainingAllowance)
    end
```

**引数**

- `message`
    送信元チェーン情報、宛先コントラクト、ガスリミットなどを含むメッセージ構造体。
- `amount`
    送付されてきたトークンの量。
