概要
このコントラクトは、Avalanche Interchain Token Transfer (ICTT) のホームチェーン側で機能する、アップグレード可能なスマートコントラクトです。 このブロックチェーンのネイティブトークンを他のブロックチェーンへ送付するために、このコントラクトにロック(預け入れ)する役割を担います。
アップグレードできないバージョンのコントラクトは以下です。
説明
NativeTokenHomeUpgradeableコントラクトは、ERC20TokenHomeUpgradeableのネイティブトークン版です。 ユーザーが他のチェーンへネイティブトークン(例: AVAX)を送りたい時、このコントラクトにネイティブトークンを送付します。 コントラクトは受け取ったネイティブトークンをロックし、リモートチェーン上のTokenRemoteコントラクトに対してトークンをMint(発行)するよう指示するクロスチェーンメッセージを送信します。
ネイティブトークン自体はコントラクトではないため、このコントラクトは内部でWrapped Native Tokenコントラクト(WAVAXなど)と連携して動作します。 ユーザーから預かったネイティブトークンはラップされ、ERC20トークンとして残高が管理されます。 トークンを引き出す時は、ラップされたトークンをアンラップしてネイティブトークンに戻し、ユーザーに送付します。
このコントラクトはアップグレード可能であるため、constructorの代わりにinitialize関数で初期設定を行い、将来のロジック更新に対応しています。
また、ERC7201規格に準拠したストレージ管理により、アップグレード時の安全性も確保されています。
ERC7201については以下の記事を参考にしてください。
機能
このコントラクトの主要な機能は以下の通りです。
- ネイティブトークンの送付 ユーザーが指定したリモートチェーンへネイティブトークンを送付する機能。
- ネイティブトークンの送付とコントラクト呼び出し ネイティブトークンを送付すると同時に、送付先チェーンのスマートコントラクトの特定の関数を呼び出す機能。
- 担保の追加 リモートコントラクトの準備金として、追加でネイティブトークンを預け入れる機能。
- ネイティブトークンの引き出し リモートチェーンからトークンが返却された時に、ロックを解除してユーザーにネイティブトークンを返還する機能。
フロー
- ネイティブトークンの送付 (
send) - ネイティブトークンの引き出し (
_withdraw) - 送付とコントラクト呼び出しの処理 (
_handleSendAndCall)
ネイティブトークンの送付 (send)
sequenceDiagram
participant User as ユーザー
participant NTHU as NativeTokenHomeUpgradeable
participant WNT as Wrapped Native Token
participant TH as TokenHome (親)
User->>NTHU: send(input) を呼び出し (msg.valueと共に)
NTHU->>TH: _send(input, msg.value) を実行
TH->>NTHU: _deposit(msg.value) を呼び出し
NTHU->>WNT: deposit() を呼び出し (msg.valueと共に)
WNT-->>NTHU: WNTをMint(発行)
NTHU-->>TH: 預かった量を返す
TH->>TH: クロスチェーンメッセージを構築・送信ネイティブトークンの引き出し (_withdraw)
sequenceDiagram
participant TH as TokenHome (親)
participant NTHU as NativeTokenHomeUpgradeable
participant WNT as Wrapped Native Token
participant Recipient as 受取人
TH->>NTHU: _withdraw(recipient, amount) を呼び出し
NTHU->>NTHU: TokensWithdrawn イベントを発行
NTHU->>WNT: withdraw(amount) を呼び出し
WNT->>NTHU: ネイティブトークンを送付 (receive()が処理)
NTHU->>Recipient: ネイティブトークンを送付 (sendValue)送付とコントラクト呼び出しの処理 (_handleSendAndCall)
sequenceDiagram
participant TH as TokenHome (親)
participant NTHU as NativeTokenHomeUpgradeable
participant WNT as Wrapped Native Token
participant RecipientContract as 宛先コントラクト
participant Fallback as フォールバックアドレス
TH->>NTHU: _handleSendAndCall(message, amount) を呼び出し
NTHU->>WNT: withdraw(amount) を呼び出し
WNT->>NTHU: ネイティブトークンを送付 (receive()が処理)
NTHU->>NTHU: receiveTokens(...) のペイロードを構築
NTHU->>RecipientContract: _callWithExactGasAndValue(gas, amount, payload)
RecipientContract-->>NTHU: 成功/失敗 (success)
alt success
NTHU->>NTHU: CallSucceeded イベントを発行
else
NTHU->>NTHU: CallFailed イベントを発行
NTHU->>Fallback: ネイティブトークンを送付 (sendValue)
endコード
構造体
NativeTokenHomeStorage
struct NativeTokenHomeStorage {
/**
* @notice The wrapped native token contract that represents the native tokens on this chain.
*/
IWrappedNativeToken _wrappedToken;
}ERC7201に従い、アップグレード時のストレージ衝突を防ぐための名前空間ストレージ構造体。 このコントラクトが連携するWrapped Native Tokenコントラクトのアドレスを保持します。
_wrappedTokenこのコントラクトがネイティブトークンをラップ/アンラップするために使用するIWrappedNativeTokenインターフェース。
変数
NATIVE_TOKEN_HOME_STORAGE_LOCATION
bytes32 public constant NATIVE_TOKEN_HOME_STORAGE_LOCATION =
0x3b5030f10c94fcbdaa3022348ff0b82dbd4c0c71339e41ff59d0bdc92179d600;NativeTokenHomeStorage構造体を格納するストレージスロットの位置を示す定数。
ERC7201規格で定められた計算式に基づいて算出された固定値で、この値を使ってインラインアセンブリで直接ストレージにアクセスします。
関数
_getNativeTokenHomeStorage
// solhint-disable ordering
function _getNativeTokenHomeStorage() private pure returns (NativeTokenHomeStorage storage $) {
// solhint-disable-next-line no-inline-assembly
assembly {
$.slot := NATIVE_TOKEN_HOME_STORAGE_LOCATION
}
}NativeTokenHomeStorage構造体へのストレージポインタを取得する内部関数。
インラインアセンブリを使用し、定数NATIVE_TOKEN_HOME_STORAGE_LOCATIONで指定されたストレージスロットを読み込むことで、NativeTokenHomeStorage構造体への参照を返します。
これにより、効率的かつ安全にアップグレード可能なストレージ領域にアクセスできます。
戻り値
NativeTokenHomeStorage storage $NativeTokenHomeStorage構造体へのストレージポインタ。
constructor
constructor(
ICMInitializable init
) {
if (init == ICMInitializable.Disallowed) {
_disableInitializers();
}
}コントラクトの初期化を制御する初期化関数。
このconstructorは、このコントラクトを継承するアップグレードできないコントラクトが、initialize関数を複数回呼び出せないように制御するために存在します。
引数initにDisallowedが渡された時、_disableInitializersを呼び出してinitialize関数の実行を永久に禁止します。
sequenceDiagram
participant Deployer as デプロイ者
participant Self as NativeTokenHomeUpgradeable
Deployer->>Self: constructor(init)
alt init is Disallowed
Self->>Self: _disableInitializers()
end引数
init初期化を許可するかどうかを示すICMInitializable型のenum値。
initialize
/**
* @notice Initializes this token TokenHome instance to send native tokens to TokenRemote instances on other chains.
* Always uses a {tokenDecimals} value of 18 since it is the denomination of the native token of EVM instances.
* @param teleporterRegistryAddress The current blockchain ID's Teleporter registry
* address. See here for details: https://github.com/ava-labs/icm-contracts/tree/main/contracts/teleporter/registry
* @param teleporterManager Address that manages this contract's integration with the
* Teleporter registry and Teleporter versions.
* @param minTeleporterVersion Minimum Teleporter version supported by this contract.
* @param wrappedTokenAddress The wrapped native token contract address of the native asset
* to be transferred to TokenRemote instances.
*/
function initialize(
address teleporterRegistryAddress,
address teleporterManager,
uint256 minTeleporterVersion,
address wrappedTokenAddress
) public initializer {
__NativeTokenHome_init(
teleporterRegistryAddress, teleporterManager, minTeleporterVersion, wrappedTokenAddress
);
}アップグレード可能なコントラクトとして、初期設定を行うための関数。
constructorの代わりに使用される初期化関数です。
initializer Modifierにより、この関数が一度しか呼び出されないことが保証されます。
内部で__NativeTokenHome_initを呼び出し、コントラクトの初期設定をすべて行います。
sequenceDiagram
participant Owner as オーナー
participant Self as NativeTokenHomeUpgradeable
Owner->>Self: initialize(...)
Self->>Self: __NativeTokenHome_init(...)引数
teleporterRegistryAddressTeleporterレジストリコントラクトのアドレス。teleporterManagerTeleporterメッセージを管理するTeleporterManagerのアドレス。minTeleporterVersionサポートするTeleporterの最低バージョン。wrappedTokenAddress連携するWrapped Native Tokenコントラクトのアドレス。
__NativeTokenHome_init
// solhint-disable-next-line func-name-mixedcase
function __NativeTokenHome_init(
address teleporterRegistryAddress,
address teleporterManager,
uint256 minTeleporterVersion,
address wrappedTokenAddress
) internal onlyInitializing {
__TokenHome_init(
teleporterRegistryAddress,
teleporterManager,
minTeleporterVersion,
wrappedTokenAddress,
18
);
__NativeTokenHome_init_unchained(wrappedTokenAddress);
}このコントラクトと親コントラクトの初期化ロジックをまとめて実行する内部関数。
onlyInitializing Modifierにより、initialize関数からのみ呼び出せるように制限されています。まず親コントラクトの__TokenHome_initを呼び出します。その時、ネイティブトークンの小数桁数は常に18であるため、tokenDecimalsには18をハードコードして渡します。
次に__NativeTokenHome_init_unchainedを呼び出してこのコントラクトの変数を初期化します。
sequenceDiagram
participant Caller as initialize()
participant Self as NativeTokenHomeUpgradeable
participant Parent as TokenHome
Caller->>Self: __NativeTokenHome_init(...)
Self->>Parent: __TokenHome_init(..., wrappedTokenAddress, 18)
Self->>Self: __NativeTokenHome_init_unchained(...)引数
teleporterRegistryAddressTeleporterレジストリコントラクトのアドレス。teleporterManagerTeleporterメッセージを管理するTeleporterManagerのアドレス。minTeleporterVersionサポートするTeleporterの最低バージョン。wrappedTokenAddress連携するWrapped Native Tokenコントラクトのアドレス。
__NativeTokenHome_init_unchained
// solhint-disable-next-line func-name-mixedcase
function __NativeTokenHome_init_unchained(
address wrappedTokenAddress
) internal onlyInitializing {
_getNativeTokenHomeStorage()._wrappedToken = IWrappedNativeToken(wrappedTokenAddress);
}このコントラクトの変数を初期化するための内部関数。
onlyInitializing Modifierで保護されています。
_getNativeTokenHomeStorageを呼び出してストレージ構造体を取得し、連携対象となるWrapped Native Tokenコントラクトのアドレスを変数_wrappedTokenに設定します。
sequenceDiagram
participant Caller as __NativeTokenHome_init()
participant Self as NativeTokenHomeUpgradeable
Caller->>Self: __NativeTokenHome_init_unchained(wrappedTokenAddress)
Self->>Self: _getNativeTokenHomeStorage()
Self->>Self: _wrappedToken 変数に wrappedTokenAddress を保存引数
wrappedTokenAddress連携対象のWrapped Native Tokenコントラクトのアドレス。
receive
/**
* @notice Receives native tokens transferred to this contract.
* @dev This function is called when the token transferrer is withdrawing native tokens to
* transfer to the recipient. The caller must be the wrapped native token contract.
*/
receive() external payable {
// The caller here is expected to be {tokenAddress} directly, and not through a meta-transaction,
// so we check for `msg.sender` instead of `_msgSender()`.
require(
msg.sender == address(_getNativeTokenHomeStorage()._wrappedToken),
"NativeTokenHome: invalid receive payable sender"
);
}ネイティブトークンを受け取るための関数。
このreceive関数は、関数を指定せずに、このコントラクトアドレスへ直接ネイティブトークンが送付された時に実行されます。
このコントラクトでは、_withdraw関数内部でWrapped Native Tokenコントラクトのwithdrawが呼び出され、その結果としてアンラップされたネイティブトークンがこのコントラクトに送り返されてくる、という特定の状況を想定しています。
そのため、送金元であるmsg.senderが、あらかじめ登録されたWrapped Native Tokenコントラクトのアドレスと一致することを検証し、意図しない入金を防いでいます。
send
/**
* @dev See {INativeTokenTransferrer-send}
*/
function send(
SendTokensInput calldata input
) external payable {
_send(input, msg.value);
}リモートチェーンにネイティブトークンを送付するための関数。
payable修飾子により、ネイティブトークンをトランザクションと共に受け取ることができます。
受け取ったネイティブトークンの量 (msg.value) をamountとして、親コントラクトの_send関数を呼び出します。
sequenceDiagram
participant User as ユーザー
participant Self as NativeTokenHomeUpgradeable
participant Parent as TokenHome
User->>Self: send(input) with msg.value
Self->>Parent: _send(input, msg.value)引数
input送付先チェーンID、受取人アドレスなどを含むSendTokensInput構造体。
sendAndCall
/**
* @dev See {INativeTokenTransferrer-sendAndCall}
*/
function sendAndCall(
SendAndCallInput calldata input
) external payable {
_sendAndCall({
sourceBlockchainID: getBlockchainID(),
originTokenTransferrerAddress: address(this),
originSenderAddress: _msgSender(),
input: input,
amount: msg.value
});
}トークンを送付して送付先チェーンのコントラクトを呼び出すための関数。
payable修飾子でネイティブトークンを受け取ります。
引数を整形し、親コントラクトTokenHomeに実装されている_sendAndCall関数を呼び出します。
送付額amountにはmsg.valueが使用されます。
sequenceDiagram
participant User as ユーザー
participant Self as NativeTokenHomeUpgradeable
participant Parent as TokenHome
User->>Self: sendAndCall(input) with msg.value
Self->>Parent: _sendAndCall(...)引数
input宛先コントラクトアドレス、ガスリミット、呼び出しデータなどを含むSendAndCallInput構造体。
addCollateral
/**
* @dev See {INativeTokenHome-addCollateral}
*/
function addCollateral(
bytes32 remoteBlockchainID,
address remoteTokenTransferrerAddress
) external payable {
_addCollateral(remoteBlockchainID, remoteTokenTransferrerAddress, msg.value);
}特定のリモートコントラクトの担保を追加するための関数。
payable修飾子でネイティブトークンを受け取ります。
受け取った量 (msg.value) をamountとして、親コントラクトの_addCollateral関数を呼び出します。
sequenceDiagram
participant User as ユーザー
participant Self as NativeTokenHomeUpgradeable
participant Parent as TokenHome
User->>Self: addCollateral(...) with msg.value
Self->>Parent: _addCollateral(..., msg.value)引数
remoteBlockchainID担保を追加するリモートコントラクトが存在するチェーンのID。remoteTokenTransferrerAddress担保を追加するリモートコントラクトのアドレス。
_deposit
/**
* @dev See {TokenHome-_deposit}
* Deposits the native tokens sent to this contract
*/
function _deposit(
uint256 amount
) internal virtual override returns (uint256) {
NativeTokenHomeStorage storage $ = _getNativeTokenHomeStorage();
return SafeWrappedNativeTokenDeposit.safeDeposit($._wrappedToken, amount);
}受け取ったネイティブトークンをWrapped Native Tokenにラップして預け入れる内部関数。
親コントラクトTokenHomeの同名関数をオーバーライドしています。SafeWrappedNativeTokenDeposit.safeDepositライブラリを使用し、指定されたamountのネイティブトークンを、登録されたWrapped Native Tokenコントラクトに安全に預け入れ(ラップし)ます。
sequenceDiagram
participant Caller as 親コントラクト (TokenHome)
participant Self as NativeTokenHomeUpgradeable
participant WNT as Wrapped Native Token
Caller->>Self: _deposit(amount)
Self->>Self: _getNativeTokenHomeStorage()
Self->>WNT: safeDeposit(amount)
WNT-->>Self: 実際に預け入れた量
Self-->>Caller: 実際に預け入れた量を返す引数
amount預け入れるネイティブトークンの量。
戻り値
uint256実際にラップされたトークンの量。
_withdraw
/**
* @dev See {TokenHome-_withdraw}
* Withdraws the wrapped tokens for native tokens,
* and sends them to the recipient.
*/
function _withdraw(address recipient, uint256 amount) internal virtual override {
NativeTokenHomeStorage storage $ = _getNativeTokenHomeStorage();
emit TokensWithdrawn(recipient, amount);
$._wrappedToken.withdraw(amount);
payable(recipient).sendValue(amount);
}ロックされていたネイティブトークンを受取人に返還するための内部関数。
親コントラクトTokenHomeの同名関数をオーバーライドしています。
まずTokensWithdrawnイベントを発行します。
次に、Wrapped Native Tokenコントラクトのwithdraw関数を呼び出して、amount分のトークンをアンラップします。
この時、アンラップされたネイティブトークンはreceive関数経由でこのコントラクトに送られます。
最後に、sendValueを使って、アンラップされたネイティブトークンを指定されたrecipientに送金します。
sequenceDiagram
participant Caller as 親コントラクト (TokenHome)
participant Self as NativeTokenHomeUpgradeable
participant WNT as Wrapped Native Token
participant Recipient as 受取人
Caller->>Self: _withdraw(recipient, amount)
Self->>Self: TokensWithdrawn イベントを発行
Self->>WNT: withdraw(amount)
WNT->>Self: ネイティブトークンを送付 (receive()が処理)
Self->>Recipient: sendValue(amount)引数
recipientネイティブトークンを受け取るアドレス。amount引き出すネイティブトークンの量。
_handleSendAndCall
/**
* @dev See {TokenHome-_handleSendAndCall}
*
* Send the native tokens to the recipient contract as a part of the call to
* {INativeSendAndCallReceiver-receiveTokens} on the recipient contract.
* If the call fails or doesn't spend all of the tokens, the remaining amount is
* sent to the fallback recipient.
*/
function _handleSendAndCall(
SingleHopCallMessage memory message,
uint256 amount
) internal virtual override {
NativeTokenHomeStorage storage $ = _getNativeTokenHomeStorage();
// Withdraw the native token from the wrapped native token contract.
$._wrappedToken.withdraw(amount);
// Encode the call to {INativeSendAndCallReceiver-receiveTokens}
bytes memory payload = abi.encodeCall(
INativeSendAndCallReceiver.receiveTokens,
(
message.sourceBlockchainID,
message.originTokenTransferrerAddress,
message.originSenderAddress,
message.recipientPayload
)
);
// Call the recipient contract with the given payload, gas amount, and value.
bool success = CallUtils._callWithExactGasAndValue(
message.recipientGasLimit, amount, message.recipientContract, payload
);
// If the call failed, send the funds to the fallback recipient.
if (success) {
emit CallSucceeded(message.recipientContract, amount);
} else {
emit CallFailed(message.recipientContract, amount);
payable(message.fallbackRecipient).sendValue(amount);
}
}リモートチェーンから送られてきたsendAndCallメッセージを処理する内部関数。
親コントラクトの同名関数をオーバーライドしています。
まず、Wrapped Native Tokenコントラクトのwithdrawを呼び出して、amount分のネイティブトークンを準備します。
次に、宛先コントラクトのreceiveTokens関数を呼び出すためのペイロードを構築します。
_callWithExactGasAndValueを使い、準備したネイティブトークン (amount) をmsg.valueとして、宛先コントラクトを呼び出します。
呼び出しが成功すればCallSucceededイベントを、失敗すればCallFailedイベントを発行し、ネイティブトークンをフォールバックアドレスに送金します。
sequenceDiagram
participant Caller as 親コントラクト (TokenHome)
participant Self as NativeTokenHomeUpgradeable
participant WNT as Wrapped Native Token
participant Recipient as 宛先コントラクト
participant Fallback as フォールバックアドレス
Caller->>Self: _handleSendAndCall(message, amount)
Self->>WNT: withdraw(amount)
WNT->>Self: ネイティブトークンを送付 (receive()が処理)
Self->>Self: receiveTokens(...) のペイロードを構築
Self->>Recipient: _callWithExactGasAndValue(gas, amount, payload)
Recipient-->>Self: 成功/失敗 (success)
alt success
Self->>Self: CallSucceeded イベントを発行
else
Self->>Self: CallFailed イベントを発行
Self->>Fallback: sendValue(amount)
end引数
message送信元チェーン情報、宛先コントラクト、ガスリミットなどを含むメッセージ構造体。amount送付されてきたネイティブトークンの量。
