概要
このコントラクトは、Avalanche Interchain Token Transfer (ICTT) のリモートチェーン側で機能する、アップグレード可能なスマートコントラクトです。 連携するTokenHomeコントラクトから送られてきたトークンを表す、新しいERC20トークンをこのチェーン上でMint(発行)・Burnします。
アップグレードできないバージョンのコントラクトは以下です。
ERC20TokenRemoteUpgradeableコントラクトは、リモートチェーン上でブリッジされたERC20トークンの実体となるコントラクトです。
TokenRemoteの抽象ロジックを継承し、ERC20トークンとしての機能(ERC20Upgradeableを継承)を併せ持っています。
TokenHomeコントラクトからトークンが送付されてくると、このコントラクトは対応する量のERC20トークンをMint(発行)して受取人に渡します。 逆に、ユーザーがこのコントラクトのERC20トークンをホームチェーンに戻したい時は、このコントラクトがトークンをBurnし、TokenHomeコントラクトにその旨を伝えるメッセージを送信します。
このコントラクトはアップグレード可能であり、initialize関数で初期設定を行います。
ERC7201規格に準拠したストレージ管理により、将来のロジック更新時も安全にデータを引き継ぐことができます。
ERC7201については以下の記事を参考にしてください。
機能
このコントラクトの主要な機能は以下です。
- ERC20トークンとしての機能
標準的な
transfer、approve、balanceOfなどのERC20インターフェースをすべて備えています。 - トークンのMint(発行) TokenHomeコントラクトからのメッセージに応じて、このコントラクトのERC20トークンをMint(発行)します。
- トークンのBurn ユーザーがトークンをホームチェーンに戻す時、または他のリモートチェーンへ送付する時にこのコントラクトのERC20トークンをBurnします。
- 送付とコントラクト呼び出し このコントラクトのERC20トークンを他のコントラクトに渡して関数を呼び出させる機能を提供します。
フロー
- トークンの受信とMint(発行) (
_withdraw) - トークンの送付とBurn (
send->_burn) sendAndCallメッセージの処理 (_handleSendAndCall)
トークンの受信とMint(発行) (_withdraw)
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)
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をリセットコード
構造体
ERC20TokenRemoteStorage
struct ERC20TokenRemoteStorage {
uint8 _decimals;
}ERC7201に準拠した、アップグレード時のストレージ衝突を防ぐための名前空間ストレージ構造体。 このERC20トークンの小数点の桁数を保持します。
_decimalsこのコントラクトが実装するERC20トークンの小数点の桁数。
変数
ERC20_TOKEN_REMOTE_STORAGE_LOCATION
bytes32 public constant ERC20_TOKEN_REMOTE_STORAGE_LOCATION =
0x9b9029a3537fcf0e984763da4ac33bbf592a3462819171bf424e91cf62622300;ERC20TokenRemoteStorage構造体を格納するストレージスロットの位置を示す定数。
ERC7201で定められた計算式に基づいて算出された固定値です。
関数
_getERC20TokenRemoteStorage
// 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
constructor(
ICMInitializable init
) {
if (init == ICMInitializable.Disallowed) {
_disableInitializers();
}
}コントラクトの初期化を制御するための初期化関数。
このconstructorは、このコントラクトを継承するアップグレードできないコントラクトが、initialize関数を複数回呼び出せないように制御するために存在します。
引数initにDisallowedが渡された時、_disableInitializersを呼び出してinitialize関数の実行を永久に禁止します。
sequenceDiagram
participant Deployer as デプロイ者
participant Self as ERC20TokenRemoteUpgradeable
Deployer->>Self: constructor(init)
alt init is Disallowed
Self->>Self: _disableInitializers()
end引数
initICMInitializable型のenum値で、初期化を許可するかどうかを示します。
initialize
/**
* @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を呼び出し、コントラクトの初期設定をすべて行います。
sequenceDiagram
participant Owner as オーナー
participant Self as ERC20TokenRemoteUpgradeable
Owner->>Self: initialize(...)
Self->>Self: __ERC20TokenRemote_init(...)引数
settingsTeleporter関連のアドレスや連携するTokenHomeコントラクトの情報を含むTokenRemoteSettings構造体。tokenNameこのコントラクトが実装するERC20トークンの名前。tokenSymbolこのコントラクトが実装するERC20トークンのシンボル。tokenDecimalsこのコントラクトが実装するERC20トークンの小数点の桁数。
__ERC20TokenRemote_init
// 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を呼び出してこのコントラクトの変数を初期化します。
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)引数
settingsTokenRemoteSettings構造体。tokenNameERC20トークンの名前。tokenSymbolERC20トークンのシンボル。tokenDecimalsERC20トークンの小数点の桁数。
__ERC20TokenRemote_init_unchained
// solhint-disable-next-line func-name-mixedcase
function __ERC20TokenRemote_init_unchained(
uint8 tokenDecimals
) internal {
_getERC20TokenRemoteStorage()._decimals = tokenDecimals;
}このコントラクトの変数を初期化するための内部関数。
__ERC20TokenRemote_initから呼び出されます。
_getERC20TokenRemoteStorageを呼び出してストレージ構造体を取得し、このERC20トークンの小数点の桁数を変数_decimalsに設定します。
sequenceDiagram
participant Caller as __ERC20TokenRemote_init()
participant Self as ERC20TokenRemoteUpgradeable
Caller->>Self: __ERC20TokenRemote_init_unchained(decimals)
Self->>Self: _getERC20TokenRemoteStorage()
Self->>Self: _decimals 変数に tokenDecimals を保存引数
tokenDecimalsERC20トークンの小数点の桁数。
send
/**
* @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関数内で、送付先に応じたシングルホップまたはマルチホップの処理が実行されます。
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
/**
* @dev See {IERC20TokenTransferrer-sendAndCall}
*/
function sendAndCall(SendAndCallInput calldata input, uint256 amount) external {
_sendAndCall(input, amount);
}このERC20トークンを送付して送付先チェーンのコントラクトを呼び出すための関数。
受け取った引数をそのまま、親コントラクトTokenRemoteに実装されている_sendAndCall関数を呼び出します。
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
/**
* @dev See {ERC20-decimals}
*/
function decimals() public view override returns (uint8) {
ERC20TokenRemoteStorage storage $ = _getERC20TokenRemoteStorage();
return $._decimals;
}このERC20トークンの小数点の桁数を返す関数。
OpenZeppelinのERC20Upgradeableのdecimals関数をオーバーライドしています。
_getERC20TokenRemoteStorageを介して変数_decimalsを読み込み、その値を返します。
戻り値
uint8トークンの小数点の桁数。
_withdraw
/**
* @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(発行)します。
sequenceDiagram
participant Caller as 親コントラクト (TokenRemote)
participant Self as ERC20TokenRemoteUpgradeable
Caller->>Self: _withdraw(recipient, amount)
Self->>Self: TokensWithdrawn イベントを発行
Self->>Self: _mint(recipient, amount) (ERC20機能)引数
recipientトークンを受け取るアドレス。amountMint(発行)するトークンの量。
_burn
/**
* @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した量を返します。
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 を返す引数
amountBurnするトークンの量。
戻り値
uint256実際にBurnされたトークンの量。
_handleSendAndCall
/**
* @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します。
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
/**
* @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します。
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実際に確保された手数料の額。
