# ERC20TokenRemoteUpgradeable

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

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

## 概要

このコントラクトは、Avalanche Interchain Token Transfer (ICTT) のリモートチェーン側で機能する、アップグレード可能なスマートコントラクトです。
連携する**TokenHome**コントラクトから送られてきたトークンを表す、新しい**ERC20**トークンをこのチェーン上でMint（発行）・Burnします。

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

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

**ERC20TokenRemoteUpgradeable**コントラクトは、リモートチェーン上でブリッジされた**ERC20**トークンの実体となるコントラクトです。
**TokenRemote**の抽象ロジックを継承し、**ERC20**トークンとしての機能（`ERC20Upgradeable`を継承）を併せ持っています。

**TokenHome**コントラクトからトークンが送付されてくると、このコントラクトは対応する量の**ERC20**トークンをMint（発行）して受取人に渡します。
逆に、ユーザーがこのコントラクトの**ERC20**トークンをホームチェーンに戻したい時は、このコントラクトがトークンをBurnし、**TokenHome**コントラクトにその旨を伝えるメッセージを送信します。

このコントラクトはアップグレード可能であり、`initialize`関数で初期設定を行います。
**ERC7201**規格に準拠したストレージ管理により、将来のロジック更新時も安全にデータを引き継ぐことができます。

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

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

## 機能

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

* **ERC20トークンとしての機能**
    標準的な`transfer`、`approve`、`balanceOf`などの**ERC20**インターフェースをすべて備えています。
* **トークンのMint（発行）**
    **TokenHome**コントラクトからのメッセージに応じて、このコントラクトの**ERC20**トークンをMint（発行）します。
* **トークンのBurn**
    ユーザーがトークンをホームチェーンに戻す時、または他のリモートチェーンへ送付する時にこのコントラクトの**ERC20**トークンをBurnします。
* **送付とコントラクト呼び出し**
    このコントラクトの**ERC20**トークンを他のコントラクトに渡して関数を呼び出させる機能を提供します。

## フロー

* トークンの受信とMint（発行） (`_withdraw`)
* トークンの送付とBurn (`send` -> `_burn`)
* `sendAndCall`メッセージの処理 (`_handleSendAndCall`)

### トークンの受信とMint（発行） (`_withdraw`)

```mermaid
sequenceDiagram
    participant TH as TokenHome
    participant TP as Teleporter
    participant E20TRU as ERC20TokenRemoteUpgradeable
    participant Recipient as 受取人
    
    TH->>TP: メッセージを送信
    TP->>E20TRU: _receiveTeleporterMessage(...)
    E20TRU->>E20TRU: _withdraw(Recipient, amount) を呼び出し
    E20TRU->>E20TRU: TokensWithdrawn イベントを発行
    E20TRU->>E20TRU: _mint(Recipient, amount) を実行 (ERC20機能)
```

### トークンの送付とBurn (`send` -> `_burn`)

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant E20TRU as ERC20TokenRemoteUpgradeable
    participant TR as TokenRemote (親)

    User->>E20TRU: send(input, amount)
    E20TRU->>E20TRU: UserからE20TRUへのallowanceを減らす
    E20TRU->>E20TRU: Userの残高をBurnする (ERC20機能)
    E20TRU->>TR: _send(input, amount) を呼び出し```

### `sendAndCall`メッセージの処理 (`_handleSendAndCall`)

```mermaid
sequenceDiagram
    participant TH as TokenHome
    participant TP as Teleporter
    participant E20TRU as ERC20TokenRemoteUpgradeable
    participant RecipientContract as 宛先コントラクト
    
    TH->>TP: メッセージを送信
    TP->>E20TRU: _receiveTeleporterMessage(...)
    E20TRU->>E20TRU: _handleSendAndCall(message, amount) を呼び出し
    E20TRU->>E20TRU: 自身のアドレスにトークンをMint（発行）
    E20TRU->>E20TRU: 宛先コントラクトへのallowanceを承認
    E20TRU->>RecipientContract: receiveTokens(...) を呼び出し
    E20TRU->>E20TRU: allowanceをリセット
```

## コード

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

## 構造体

### `ERC20TokenRemoteStorage`

```sol
struct ERC20TokenRemoteStorage {
    uint8 _decimals;
}
```

**ERC7201**に準拠した、アップグレード時のストレージ衝突を防ぐための名前空間ストレージ構造体。
この**ERC20**トークンの小数点の桁数を保持します。

- `_decimals`
    このコントラクトが実装する**ERC20**トークンの小数点の桁数。

## 変数

### `ERC20_TOKEN_REMOTE_STORAGE_LOCATION`

```sol
bytes32 public constant ERC20_TOKEN_REMOTE_STORAGE_LOCATION =
    0x9b9029a3537fcf0e984763da4ac33bbf592a3462819171bf424e91cf62622300;
```

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

## 関数

### `_getERC20TokenRemoteStorage`

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

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

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

**戻り値**

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

### `constructor`

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

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

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

```mermaid
sequenceDiagram
    participant Deployer as デプロイ者
    participant Self as ERC20TokenRemoteUpgradeable
    
    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 an ERC20 token on this chain.
 * @param settings Constructor settings for this token TokenRemote instance.
 * @param tokenName The name of the ERC20 token.
 * @param tokenSymbol The symbol of the ERC20 token.
 * @param tokenDecimals The number of decimals for the ERC20 token.
 */
function initialize(
    TokenRemoteSettings memory settings,
    string memory tokenName,
    string memory tokenSymbol,
    uint8 tokenDecimals
) public initializer {
    __ERC20TokenRemote_init(settings, tokenName, tokenSymbol, tokenDecimals);
}
```

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

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

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

**引数**

- `settings`
    Teleporter関連のアドレスや連携する**TokenHome**コントラクトの情報を含む`TokenRemoteSettings`構造体。
- `tokenName`
    このコントラクトが実装する**ERC20**トークンの名前。
- `tokenSymbol`
    このコントラクトが実装する**ERC20**トークンのシンボル。
- `tokenDecimals`
    このコントラクトが実装する**ERC20**トークンの小数点の桁数。

### `__ERC20TokenRemote_init`

```sol
// solhint-disable-next-line func-name-mixedcase
function __ERC20TokenRemote_init(
    TokenRemoteSettings memory settings,
    string memory tokenName,
    string memory tokenSymbol,
    uint8 tokenDecimals
) internal onlyInitializing {
    __ERC20_init(tokenName, tokenSymbol);
    __TokenRemote_init(settings, 0, tokenDecimals);
    __ERC20TokenRemote_init_unchained(tokenDecimals);
}
```

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

`onlyInitializing` Modifierで保護されています。
`__ERC20_init`を呼び出して**ERC20**トークンとしての名前とシンボルを設定し、`__TokenRemote_init`を呼び出してICTTのリモートコントラクトとしての設定を行います。
最後に`__ERC20TokenRemote_init_unchained`を呼び出してこのコントラクトの変数を初期化します。

```mermaid
sequenceDiagram
    participant Caller as initialize()
    participant Self as ERC20TokenRemoteUpgradeable
    participant ParentERC20 as ERC20Upgradeable
    participant ParentRemote as TokenRemote
    
    Caller->>Self: __ERC20TokenRemote_init(...)
    Self->>ParentERC20: __ERC20_init(name, symbol)
    Self->>ParentRemote: __TokenRemote_init(settings, 0, decimals)
    Self->>Self: __ERC20TokenRemote_init_unchained(decimals)
```

**引数**

- `settings`
    `TokenRemoteSettings`構造体。
- `tokenName`
    **ERC20**トークンの名前。
- `tokenSymbol`
    **ERC20**トークンのシンボル。
- `tokenDecimals`
    **ERC20**トークンの小数点の桁数。

### `__ERC20TokenRemote_init_unchained`

```sol
// solhint-disable-next-line func-name-mixedcase
function __ERC20TokenRemote_init_unchained(
    uint8 tokenDecimals
) internal {
    _getERC20TokenRemoteStorage()._decimals = tokenDecimals;
}
```

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

`__ERC20TokenRemote_init`から呼び出されます。
`_getERC20TokenRemoteStorage`を呼び出してストレージ構造体を取得し、この**ERC20**トークンの小数点の桁数を変数`_decimals`に設定します。

```mermaid
sequenceDiagram
    participant Caller as __ERC20TokenRemote_init()
    participant Self as ERC20TokenRemoteUpgradeable
    
    Caller->>Self: __ERC20TokenRemote_init_unchained(decimals)
    Self->>Self: _getERC20TokenRemoteStorage()
    Self->>Self: _decimals 変数に tokenDecimals を保存
```

**引数**

- `tokenDecimals`
    **ERC20**トークンの小数点の桁数。

### `send`

```sol
/**
 * @dev See {IERC20TokenTransferrer-send}
 *
 * Note: For transfers to an {input.destinationBlockchainID} that is not the {tokenHomeBlockchainID},
 * a multi-hop transfer is performed, where the tokens are sent back to the token TokenHome instance
 * first to check for token transfer balance, and then routed to the final destination TokenRemote instance.
 */
function send(SendTokensInput calldata input, uint256 amount) external {
    _send(input, amount);
}
```

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

受け取った引数をそのまま、親コントラクト**TokenRemote**に実装されている内部関数`_send`に渡します。
`_send`関数内で、送付先に応じたシングルホップまたはマルチホップの処理が実行されます。

```mermaid
sequenceDiagram
    participant User as ユーザー
    participant Self as ERC20TokenRemoteUpgradeable
    participant Parent as TokenRemote
    
    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(input, amount);
}
```

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

受け取った引数をそのまま、親コントラクト**TokenRemote**に実装されている`_sendAndCall`関数を呼び出します。

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

**引数**

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

### `decimals`

```sol
/**
 * @dev See {ERC20-decimals}
 */
function decimals() public view override returns (uint8) {
    ERC20TokenRemoteStorage storage $ = _getERC20TokenRemoteStorage();
    return $._decimals;
}
```

この**ERC20**トークンの小数点の桁数を返す関数。

OpenZeppelinの`ERC20Upgradeable`の`decimals`関数をオーバーライドしています。
`_getERC20TokenRemoteStorage`を介して変数`_decimals`を読み込み、その値を返します。

**戻り値**

- `uint8`
    トークンの小数点の桁数。

### `_withdraw`

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

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

親コントラクト**TokenRemote**の同名関数をオーバーライドしています。
`_receiveTeleporterMessage`から呼び出されると、まず`TokensWithdrawn`イベントを発行し、次に`ERC20Upgradeable`から継承した`_mint`関数を呼び出して、指定された`recipient`に`amount`分の**ERC20**トークンをMint（発行）します。

```mermaid
sequenceDiagram
    participant Caller as 親コントラクト (TokenRemote)
    participant Self as ERC20TokenRemoteUpgradeable
    
    Caller->>Self: _withdraw(recipient, amount)
    Self->>Self: TokensWithdrawn イベントを発行
    Self->>Self: _mint(recipient, amount) (ERC20機能)
```

**引数**

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

### `_burn`

```sol
/**
 * @dev See {TokenRemote-_burn}
 *
 * Spends the allowance the caller has given to this contract, and
 * calls {ERC20-_burn} to burn tokens from the sender.
 *
 * Note: The amount returned must match the amount credited as a result of the burn.
 * For a standard ERC20 implementation such as this contract, that is equal to the full amount given.
 * Child contracts with different {_burn} implementations may need to override this
 * implemenation to ensure the amount returned is correct.
 */
function _burn(
    uint256 amount
) internal virtual override returns (uint256) {
    _spendAllowance(_msgSender(), address(this), amount);
    _burn(_msgSender(), amount);
    return amount;
}
```

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

親コントラクト**TokenRemote**の同名関数をオーバーライドしています。
送付処理の最初に呼び出されます。
まず`_spendAllowance`を呼び出して、関数実行者（`_msgSender()`）がこのコントラクトに対して承認している`allowance`を消費します。
次に、`ERC20Upgradeable`から継承した`_burn`関数を呼び出して、関数実行者の残高から`amount`分のトークンをBurnします。最後にBurnした量を返します。

```mermaid
sequenceDiagram
    participant Caller as 親コントラクト (TokenRemote)
    participant Self as ERC20TokenRemoteUpgradeable
    
    Caller->>Self: _burn(amount)
    Self->>Self: _spendAllowance(_msgSender(), this, amount)
    Self->>Self: _burn(_msgSender(), amount) (ERC20機能)
    Self-->>Caller: amount を返す
```

**引数**

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

**戻り値**

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

### `_handleSendAndCall`

```sol
/**
 * @dev See {TokenRemote-_handleSendAndCall}
 *
 * Mints the tokens to this contract, approves the recipient contract to spend them,
 * 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 {
    // Mint the tokens to this contract address.
    _mint(address(this), amount);

    // Approve the recipient contract to spend the amount.
    _approve(address(this), message.recipientContract, amount);

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

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

    // Check what the remaining allowance is to transfer to the fallback recipient.
    uint256 remainingAllowance = allowance(address(this), message.recipientContract);

    // Reset the recipient contract allowance to 0.
    _approve(address(this), 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) {
        _transfer(address(this), message.fallbackRecipient, remainingAllowance);
    }
}
```

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

親コントラクトの同名関数をオーバーライドしています。
まず`_mint`を呼び出し、このコントラクト自身のアドレスに`amount`分のトークンをMint（発行）します。
次に`_approve`を呼び出し、Mintしたトークンを宛先コントラクトが使用できるように承認します。
`receiveTokens`を呼び出すためのペイロードを構築し、`_callWithExactGas`で宛先コントラクトを呼び出します。
呼び出し後、`allowance`を確認して残量を取得し、その後`_approve`で`allowance`を0にリセットします。
呼び出しの成否に応じたイベントを発行し、もし`allowance`が残っていれば（呼び出しが失敗した場合も含む）、その残量をフォールバックアドレスに`_transfer`します。

```mermaid
sequenceDiagram
    participant Caller as 親コントラクト (TokenRemote)
    participant Self as ERC20TokenRemoteUpgradeable
    participant Recipient as 宛先コントラクト
    participant Fallback as フォールバックアドレス
    
    Caller->>Self: _handleSendAndCall(message, amount)
    Self->>Self: _mint(this, amount)
    Self->>Self: _approve(this, Recipient, amount)
    Self->>Self: receiveTokens(...) のペイロードを構築
    Self->>Recipient: _callWithExactGas(gasLimit, payload)
    Recipient-->>Self: 成功/失敗 (success)
    Self->>Self: allowance(this, Recipient)
    Self-->>Self: remainingAllowance
    Self->>Self: _approve(this, Recipient, 0)
    alt success
        Self->>Self: CallSucceeded イベントを発行
    else
        Self->>Self: CallFailed イベントを発行
    end
    
    opt remainingAllowance > 0
        Self->>Self: _transfer(this, Fallback, remainingAllowance)
    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を返します。
手数料として指定されたトークンがこのコントラクト自身 (`feeTokenAddress == address(this)`) の場合、`_spendAllowance`と`_transfer`を使ってユーザーからこのコントラクトへトークンを移動させます。
手数料トークンが外部の**ERC20**トークンの場合、`SafeERC20TransferFrom`ライブラリを使って安全にユーザーからトークンを`transferFrom`します。

```mermaid
sequenceDiagram
    participant Caller as 親コントラクト (TokenRemote)
    participant Self as ERC20TokenRemoteUpgradeable
    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`
    実際に確保された手数料の額。
