概要

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

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

説明

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

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

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

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

機能

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

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

フロー

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

ERC20トークンの送付 (send)

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)

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: (もしあれば)未使用トークンをフォールバック宛先に送付

コード

構造体

ERC20TokenHomeStorage

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

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

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

変数

ERC20_TOKEN_HOME_STORAGE_LOCATION

text
bytes32 public constant ERC20_TOKEN_HOME_STORAGE_LOCATION =
    0x914a9547f6c3ddce1d5efbd9e687708f0d1d408ce129e8e1a88bce4f40e29500;

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

関数

_getERC20TokenHomeStorage

text
// 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

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

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

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

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

引数

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

initialize

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

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

text
// 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を呼び出してこのコントラクトの初期化(トークンアドレスの設定)を行います。

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

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

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

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

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

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

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

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

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

text
/**
 * @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関数を呼び出します。

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

引数

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

addCollateral

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

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

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

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

引数

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

_deposit

text
/**
 * @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していることが前提となります。

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

text
/**
 * @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に安全に送金します。

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

text
/**
 * @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の残り)があれば、それをフォールバック用の受取人アドレスに送金します。 呼び出しが失敗した時は、全額がフォールバック宛先に送られます。

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 送付されてきたトークンの量。