概要
このコントラクトは、Avalanche Interchain Token Transfer (ICTT) のリモートチェーン側で機能する、アップグレード可能なコントラクトです。 特定のTokenHomeコントラクトから送られてきたトークンを受け取り(Mint(発行)し)、そのトークンをBurnしてホームチェーン上の担保資産を償還したり、他のリモートコントラクトへ送付したりするための基盤ロジックを提供します。
TokenRemoteコントラクトは、リモートチェーン側でトークンのMint(発行)とBurnを管理する役割を担います。 ホームチェーンのTokenHomeコントラクトからクロスチェーンメッセージを受信すると、トークンをMint(発行)してユーザーに渡します。 逆に、ユーザーがこのコントラクトのトークンをホームチェーンに戻したり、別のリモートチェーンに送付したりする時は、トークンをBurnしてTokenHomeコントラクトへそのことを伝えるメッセージを送信します。
このコントラクトは抽象 (abstract) であるため、直接デプロイすることはできません。
アセットの具体的なMint(発行)(_withdraw)、Burn(_burn)、手数料処理(_handleFees)、sendAndCallメッセージを処理する方法(_handleSendAndCall)は、これを継承するERC20TokenRemoteやNativeTokenRemoteといったコントラクトで実装される必要があります。
主な責務は以下の通りです。
- ホームコントラクトとの連携 どのTokenHomeコントラクトに紐づいているかを管理し、通信します。
- 登録 稼働を開始する前に自身をTokenHomeコントラクトに登録する機能を提供します。
- 送付ロジック シングルホップ(ホームに戻す)とマルチホップ(他リモートへ送る)の両方の送付ロジックを処理します。
- 小数桁数のスケーリング ホームとリモートでトークンの小数桁数が異なる場合に対応するため、トークン量を自動的に換算します。
- アップグレード可能性 ERC7201規格のストレージレイアウトを採用し、安全なアップグレードを可能にしています。
ERC7201については以下の記事を参考にしてください。
機能
このコントラクトが提供する中核機能は以下です。
- TokenHomeコントラクトへの登録 稼働開始時、自身の存在をTokenHomeコントラクトに通知して登録します。
- トークンの受信とMint(発行) TokenHomeコントラクトからのメッセージに基づき、トークンをMint(発行)するためのロジックを呼び出します。
- トークンの送付(Burn) ユーザーからの要求に基づきトークンをBurnし、シングルホップまたはマルチホップのメッセージをTokenHomeコントラクトへ送信します。
- 送付とコントラクト呼び出し トークンを送付すると同時に、送付先チェーンのスマートコントラクトを呼び出す機能の基盤を提供します。
フロー
- TokenHomeコントラクトへの登録 (
registerWithHome) - トークンの送付(シングルホップ)
- トークンの受信 (
_receiveTeleporterMessage)
TokenHomeコントラクトへの登録 (registerWithHome)
sequenceDiagram
participant User as ユーザー
participant TR as TokenRemote
participant TP as Teleporter
User->>TR: registerWithHome(feeInfo)
TR->>TR: _handleFees(feeInfo) (抽象)
TR->>TR: RegisterRemoteMessage を構築
TR->>TP: _sendTeleporterMessage(...)トークンの送付(シングルホップ)
sequenceDiagram
participant User as ユーザー
participant Child as 具象Remoteコントラクト
participant TR as TokenRemote
participant TP as Teleporter
User->>Child: send(input, amount)
Child->>TR: _send(input, amount)
TR->>TR: _processSend(input, amount)
TR->>TR: _prepareSend(...)
TR->>Child: _burn(amount) (抽象)
TR->>Child: _handleFees(...) (抽象)
TR->>TR: SingleHopSendMessage を構築
TR->>TP: _sendTeleporterMessage(...)トークンの受信 (_receiveTeleporterMessage)
sequenceDiagram
participant TH as TokenHome
participant TP as Teleporter
participant TR as TokenRemote
participant Child as 具象Remoteコントラクト
TH->>TP: メッセージを送信
TP->>TR: _receiveTeleporterMessage(...)
TR->>TR: 送信元とメッセージタイプを検証
TR->>TR: _isRegistered, _isCollateralized を true に更新
TR->>Child: _withdraw(recipient, amount) (抽象)コード
構造体
TokenRemoteStorage
struct TokenRemoteStorage {
/// @notice The blockchain ID of the chain this contract is deployed on.
bytes32 _blockchainID;
/// @notice The blockchain ID of the TokenHome instance this contract receives tokens from.
bytes32 _tokenHomeBlockchainID;
/// @notice The address of the TokenHome instance this contract receives tokens from on the {tokenHomeBlockchainID}.
address _tokenHomeAddress;
/**
* @notice The number of decimal places in the denomination of the home
* token.
* @dev Used to derive tokenMultiplier and multiplyOnRemote.
*/
uint8 _homeTokenDecimals;
/**
* @notice The number of decimal places in the denomination of the remote token.
* @dev Used to derive tokenMultiplier and multiplyOnRemote.
*/
uint8 _tokenDecimals;
/**
* @notice tokenMultiplier allows this contract to scale the number of tokens it sends/receives to/from
* its token TokenHome instance.
*
* @dev This is used to normalize the number of decimal places between the token home asset and the
* token remote asset. It is derived from home and remote token decimals values passed in the constructor.
*/
uint256 _tokenMultiplier;
/**
* @notice If {multiplyOnRemote} is true, the home token amount will be multiplied by {tokenMultiplier} when tokens
* are transferred from the home into this remote, and divided by {tokenMultiplier} when tokens are transferred from
* this remote back to its home.
* If {multiplyOnRemote} is false, the home token amount value will be divided by {tokenMultiplier} when tokens
* are transferred from the home into this remote, and multiplied by {tokenMultiplier} when tokens are transferred
* from this remote back to its home.
*/
bool _multiplyOnRemote;
/**
* @notice Initial reserve imbalance that the token for this TokenRemote instance starts with. The home contract must
* collateralize a corresonding amount of home tokens before tokens can be minted on this contract.
*/
uint256 _initialReserveImbalance;
/**
* @notice Whether or not the contract is known to be fully collateralized.
*/
bool _isCollateralized;
/**
* @notice Whether or not the contract is known to be registered with its specified home contract.
* This is set to true when the first message is received from the home contract. Note that {isRegistered}
* will still be false after the remote contract is registered on the home contract until the first
* message is received back from that contract.
*/
bool _isRegistered;
}ERC7201規格に準拠した、アップグレード時のストレージ衝突を防ぐための名前空間ストレージ構造体。 このコントラクトの主要な変数をすべて含みます。
_blockchainIDこのコントラクトがデプロイされているブロックチェーンのID。_tokenHomeBlockchainIDこのコントラクトが連携するTokenHomeコントラクトが存在するブロックチェーンのID。_tokenHomeAddress連携するTokenHomeコントラクトのアドレス。_homeTokenDecimalsホームトークンの小数点の桁数。_tokenDecimalsこのリモートトークンの小数点の桁数。_tokenMultiplierホームとリモートの小数桁数の差を補正するための乗数。_multiplyOnRemoteトークン量換算の時、乗算と除算のどちらを適用するかを示すフラグ。_initialReserveImbalanceこのリモートチェーンの立ち上げ時に生成された、担保のない初期トークン供給量。_isCollateralizedTokenHomeコントラクト側で初期担保が満たされたことが確認できたかを示すフラグ。_isRegisteredTokenHomeコントラクトに登録され、最初のメッセージを受信したかを示すフラグ。
変数
TOKEN_REMOTE_STORAGE_LOCATION
bytes32 public constant TOKEN_REMOTE_STORAGE_LOCATION =
0x600d6a9b283d1eda563de594ce4843869b6f128a4baa222422ed94a60b0cef00;TokenRemoteStorage構造体を格納するストレージスロットの位置を示す定数。
ERC7201規格で定められた計算式に基づいて算出された固定値です。
MULTI_HOP_SEND_REQUIRED_GAS
uint256 public constant MULTI_HOP_SEND_REQUIRED_GAS = 340_000;マルチホップ送付メッセージをTokenHomeコントラクトで処理するために必要な固定の推定ガス量。
MULTI_HOP_CALL_REQUIRED_GAS
uint256 public constant MULTI_HOP_CALL_REQUIRED_GAS = 350_000;マルチホップの「送付とコントラクト呼び出し」メッセージをTokenHomeコントラクトで処理するために必要な固定の推定ガス量。
MULTI_HOP_CALL_GAS_PER_WORD
uint256 public constant MULTI_HOP_CALL_GAS_PER_WORD = 1_500;マルチホップの「送付とコントラクト呼び出し」メッセージにおいて、宛先ペイロードのデータ長(32バイトワード単位)ごとに追加で必要となるガス量。
REGISTER_REMOTE_REQUIRED_GAS
uint256 public constant REGISTER_REMOTE_REQUIRED_GAS = 130_000;このリモートコントラクトをTokenHomeコントラクトに登録するために必要な固定の推定ガス量。
関数
_getTokenRemoteStorage
// solhint-disable ordering
function _getTokenRemoteStorage() private pure returns (TokenRemoteStorage storage $) {
// solhint-disable-next-line no-inline-assembly
assembly {
$.slot := TOKEN_REMOTE_STORAGE_LOCATION
}
}TokenRemoteStorage構造体へのストレージポインタを取得する内部関数。
インラインアセンブリを使用し、定数TOKEN_REMOTE_STORAGE_LOCATIONで指定されたストレージスロットを読み込むことで、TokenRemoteStorage構造体への参照を返します。
これにより、効率的かつ安全にアップグレード可能なストレージ領域にアクセスできます。
戻り値
TokenRemoteStorage storage $TokenRemoteStorage構造体へのストレージポインタ。
__TokenRemote_init
// solhint-disable ordering
// solhint-disable-next-line func-name-mixedcase
function __TokenRemote_init(
TokenRemoteSettings memory settings,
uint256 initialReserveImbalance_,
uint8 tokenDecimals
) internal onlyInitializing {
__TeleporterRegistryOwnableApp_init(
settings.teleporterRegistryAddress,
settings.teleporterManager,
settings.minTeleporterVersion
);
__SendReentrancyGuard_init();
__TokenRemote_init_unchained(settings, initialReserveImbalance_, tokenDecimals);
}アップグレード可能なコントラクトの初期設定を行う内部関数。
initializer Modifierを持つ公開関数から一度だけ呼び出されます。
まず、継承しているTeleporterRegistryOwnableAppUpgradeableとSendReentrancyGuardUpgradeableの初期化関数をそれぞれ呼び出します。
その後、__TokenRemote_init_unchainedを呼び出し、このコントラクトの変数を設定します。
sequenceDiagram
participant Initializer as initialize()
participant Self as TokenRemote
participant Parent1 as Teleporter..App
participant Parent2 as SendReentrancyGuard
Initializer->>Self: __TokenRemote_init(...)
Self->>Parent1: __Teleporter..._init()
Self->>Parent2: __SendReentrancyGuard_init()
Self->>Self: __TokenRemote_init_unchained(...)引数
settingsTokenRemoteSettings構造体で、Teleporter関連のアドレスや連携するTokenHomeコントラクトの情報を含みます。initialReserveImbalance_担保のない初期トークン供給量。tokenDecimalsこのリモートトークンの小数点の桁数。
__TokenRemote_init_unchained
// solhint-disable-next-line func-name-mixedcase
function __TokenRemote_init_unchained(
TokenRemoteSettings memory settings,
uint256 initialReserveImbalance_,
uint8 tokenDecimals
) internal onlyInitializing {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
$._blockchainID =
IWarpMessenger(0x0200000000000000000000000000000000000005).getBlockchainID();
require(
settings.tokenHomeBlockchainID != bytes32(0),
"TokenRemote: zero token home blockchain ID"
);
require(
settings.tokenHomeBlockchainID != $._blockchainID,
"TokenRemote: cannot deploy to same blockchain as token home"
);
require(settings.tokenHomeAddress != address(0), "TokenRemote: zero token home address");
require(
settings.tokenHomeDecimals <= TokenScalingUtils.MAX_TOKEN_DECIMALS,
"TokenRemote: token home decimals too high"
);
require(
tokenDecimals <= TokenScalingUtils.MAX_TOKEN_DECIMALS,
"TokenRemote: token decimals too high"
);
$._tokenHomeBlockchainID = settings.tokenHomeBlockchainID;
$._tokenHomeAddress = settings.tokenHomeAddress;
$._initialReserveImbalance = initialReserveImbalance_;
$._isCollateralized = initialReserveImbalance_ == 0;
$._homeTokenDecimals = settings.tokenHomeDecimals;
$._tokenDecimals = tokenDecimals;
($._tokenMultiplier, $._multiplyOnRemote) =
TokenScalingUtils.deriveTokenMultiplierValues(settings.tokenHomeDecimals, tokenDecimals);
}このコントラクトの変数を初期化するための内部関数。
onlyInitializing Modifierで保護されています。
まず、Warp Messengerプリコンパイルから自身のチェーンIDを取得し、引数で渡された設定値の検証を行います。
その後、TokenHomeのチェーンIDやアドレス、初期供給量などの変数をストレージに保存します。
最後に、TokenScalingUtils.deriveTokenMultiplierValuesを呼び出して、小数桁数の差を補正するための乗数と計算方法を決定して保存します。
sequenceDiagram
participant Init as __TokenRemote_init
participant Self as TokenRemote
participant Warp as Warp Messenger Precompile
participant Utils as TokenScalingUtils
Init->>Self: __TokenRemote_init_unchained(...)
Self->>Self: 引数を検証 (require)
Self->>Warp: getBlockchainID()
Warp-->>Self: チェーンIDを返す
Self->>Utils: deriveTokenMultiplierValues(...)
Utils-->>Self: _tokenMultiplier, _multiplyOnRemote を返す
Self->>Self: 全ての変数をストレージに保存引数
settingsTokenRemoteSettings構造体。initialReserveImbalance_担保のない初期トークン供給量。tokenDecimalsこのリモートトークンの小数点の桁数。
registerWithHome
/**
* @notice Sends a message to the contract's specified token TokenHome instance to register this remote
* instance. TokenRemote instances must be registered with their home contract prior to being able to receive
* tokens from them.
*/
function registerWithHome(
TeleporterFeeInfo calldata feeInfo
) external virtual {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
require(!$._isRegistered, "TokenRemote: already registered");
// Send a message to the token TokenHome instance to register this TokenRemote instance.
RegisterRemoteMessage memory registerMessage = RegisterRemoteMessage({
initialReserveImbalance: $._initialReserveImbalance,
homeTokenDecimals: $._homeTokenDecimals,
remoteTokenDecimals: $._tokenDecimals
});
TransferrerMessage memory message = TransferrerMessage({
messageType: TransferrerMessageType.REGISTER_REMOTE,
payload: abi.encode(registerMessage)
});
uint256 feeAmount = _handleFees(feeInfo.feeTokenAddress, feeInfo.amount);
_sendTeleporterMessage(
TeleporterMessageInput({
destinationBlockchainID: $._tokenHomeBlockchainID,
destinationAddress: $._tokenHomeAddress,
feeInfo: TeleporterFeeInfo({feeTokenAddress: feeInfo.feeTokenAddress, amount: feeAmount}),
requiredGasLimit: REGISTER_REMOTE_REQUIRED_GAS,
allowedRelayerAddresses: new address[](0),
message: abi.encode(message)
})
);
}このリモートコントラクトを、連携するTokenHomeコントラクトに登録するための関数。
まだ登録されていないこと (!_isRegistered) を確認します。
次に、RegisterRemoteMessageを構築し、TransferrerMessageでラップします。
_handleFeesを呼び出してメッセージ手数料を処理した後、_sendTeleporterMessageを呼び出して、TokenHomeコントラクトへ登録メッセージを送信します。
sequenceDiagram
participant User as ユーザー
participant Self as TokenRemote
participant TP as Teleporter
User->>Self: registerWithHome(feeInfo)
Self->>Self: _isRegistered を検証
Self->>Self: RegisterRemoteMessage を構築
Self->>Self: _handleFees(feeInfo) (抽象)
Self-->>Self: feeAmount を受け取る
Self->>TP: _sendTeleporterMessage(...)引数
feeInfoTeleporterメッセージのrelayerに支払う手数料の情報。
calculateNumWords
/**
* @dev Calculates the number of 32-byte words required to fit a payload of a given length.
* The payloads are padded to have a length that is a multiple of 32.
*/
function calculateNumWords(
uint256 payloadSize
) public pure returns (uint256) {
// Add 31 to effectively round up to the nearest multiple of 32.
// Right-shift by 5 bits to divide by 32.
return (payloadSize + 31) >> 5;
}与えられたバイトサイズが、32バイトのワード単位でいくつになるかを計算する関数。
ペイロードのガス代を計算するために使用されるヘルパー関数です。
与えられたpayloadSizeを32で割った時の切り上げの整数を計算します。
引数
payloadSize計算対象のペイロードのバイトサイズ。
戻り値
uint25632バイトを1ワードとした時のワード数。
getIsCollateralized
function getIsCollateralized() public view returns (bool) {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
return $._isCollateralized;
}このコントラクトが完全に担保されているかどうかの状態を返す関数。
変数_isCollateralizedの値を返します。
この値は、TokenHomeコントラクトから最初のメッセージを受信した時にtrueになります。
連携しているTokenHomeコントラクトには、「リモートが必要とする初期担保がすべて満たされるまで、そのリモートへのトークン送付メッセージを一切送信しない」というルールがあります。
そのため、このTokenRemoteコントラクトがTokenHomeから最初のメッセージを受信したという事実は、その時点で初期担保が既に満たされていることの証明になります。
そのため、このコントラクトはメッセージを受信したタイミングで、自身の_isCollateralizedフラグを安全にtrueに更新することができます。
戻り値
bool完全に担保されていればtrue、そうでなければfalse。
getTokenMultiplier
function getTokenMultiplier() public view returns (uint256) {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
return $._tokenMultiplier;
}ホームトークンとリモートトークン間の小数桁数補正に使う乗数を返す関数。
変数_tokenMultiplierの値を返します。
戻り値
uint256トークン量の換算に使用される乗数。
getMultiplyOnRemote
function getMultiplyOnRemote() public view returns (bool) {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
return $._multiplyOnRemote;
}トークン量換算の計算方法を示すフラグを返す関数。
変数_multiplyOnRemoteの値を返します。
このフラグがtrueかfalseかによって、_tokenMultiplierを乗算するか除算するかが決まります。
戻り値
boolトークン量換算の計算方法を示すフラグ。
getTokenHomeBlockchainID
function getTokenHomeBlockchainID() public view returns (bytes32) {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
return $._tokenHomeBlockchainID;
}連携するTokenHomeコントラクトが存在するブロックチェーンのIDを返す関数。
変数_tokenHomeBlockchainIDの値を返します。
戻り値
bytes32TokenHomeコントラクトのチェーンID。
getTokenHomeAddress
function getTokenHomeAddress() public view returns (address) {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
return $._tokenHomeAddress;
}連携するTokenHomeコントラクトのアドレスを返す関数。
変数_tokenHomeAddressの値を返します。
戻り値
addressTokenHomeコントラクトのアドレス。
getInitialReserveImbalance
function getInitialReserveImbalance() public view returns (uint256) {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
return $._initialReserveImbalance;
}担保のない初期トークン供給量を返す関数。
変数_initialReserveImbalanceの値を返します。
戻り値
uint256担保のない初期トークン供給量。
getBlockchainID
function getBlockchainID() public view returns (bytes32) {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
return $._blockchainID;
}このコントラクトがデプロイされているブロックチェーンのIDを返す関数。
変数_blockchainIDの値を返します。
戻り値
bytes32このコントラクトのチェーンID。
_send
/**
* @notice Sends tokens to the specified destination.
*
* @dev Burns the transferred amount, and uses Teleporter to send a cross chain message to the token TokenHome instance.
* Tokens can be sent the token TokenHome instance, or to any TokenRemote instance registered with the home other than this one.
*/
function _send(SendTokensInput calldata input, uint256 amount) internal sendNonReentrant {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
_validateSendTokensInput(input);
if (input.destinationBlockchainID == $._tokenHomeBlockchainID) {
_processSend(input, amount);
} else {
_processSendMultiHop(input, amount);
}
}トークンを送付するための内部関数。
sendNonReentrant Modifierで保護されています。
入力値を検証した後、送付先がTokenHomeコントラクトのチェーン(_tokenHomeBlockchainID)であれば、シングルホップ処理の_processSendを呼び出します。
そうでなければ、マルチホップ処理の_processSendMultiHopを呼び出します。
sequenceDiagram
participant Caller as 継承先コントラクト
participant Self as TokenRemote
Caller->>Self: _send(input, amount)
Self->>Self: _validateSendTokensInput(input)
alt destination is TokenHome
Self->>Self: _processSend(input, amount)
else destination is another Remote
Self->>Self: _processSendMultiHop(input, amount)
end引数
input送付先情報などを含むSendTokensInput構造体。amount送付するトークンの量。
_sendAndCall
/**
* @notice Sends tokens to the specified recipient contract on the destination blockchain ID by
* calling the {receiveTokens} method of the respective recipient.
*
* @dev Burns the transferred amount, and uses Teleporter to send a cross chain message.
* Tokens and data can be sent to the token TokenHome instance, or to any TokenRemote instance registered with the home
* other than this one.
*/
function _sendAndCall(
SendAndCallInput calldata input,
uint256 amount
) internal sendNonReentrant {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
_validateSendAndCallInput(input);
if (input.destinationBlockchainID == $._tokenHomeBlockchainID) {
return _processSendAndCall(input, amount);
} else {
return _processSendAndCallMultiHop(input, amount);
}
}トークンを送付して宛先コントラクトを呼び出すための内部関数。
sendNonReentrant Modifierで保護されています。
入力値を検証した後、送付先がTokenHomeコントラクトのチェーンであれば、シングルホップ処理の_processSendAndCallを呼び出します。
そうでなければ、マルチホップ処理の_processSendAndCallMultiHopを呼び出します。
sequenceDiagram
participant Caller as 継承先コントラクト
participant Self as TokenRemote
Caller->>Self: _sendAndCall(input, amount)
Self->>Self: _validateSendAndCallInput(input)
alt destination is TokenHome
Self->>Self: _processSendAndCall(input, amount)
else destination is another Remote
Self->>Self: _processSendAndCallMultiHop(input, amount)
end引数
input宛先コントラクト情報などを含むSendAndCallInput構造体。amount送付するトークンの量。
_receiveTeleporterMessage
/**
* @notice Handles receiving messages from the token TokenHome instance. The supported message types are
* single-hop sends, and single-hop calls.
*
* @dev See {ITeleporterUpgradeable-_receiveTeleporterMessage}
*/
function _receiveTeleporterMessage(
bytes32 sourceBlockchainID,
address originSenderAddress,
bytes memory message
) internal override {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
require(
sourceBlockchainID == $._tokenHomeBlockchainID,
"TokenRemote: invalid source blockchain ID"
);
require(
originSenderAddress == $._tokenHomeAddress, "TokenRemote: invalid origin sender address"
);
TransferrerMessage memory transferrerMessage = abi.decode(message, (TransferrerMessage));
// If the contract was not previously known to be registered or collateralized, it is now given that
// the home has sent a message to mint funds.
if (!$._isRegistered || !$._isCollateralized) {
$._isRegistered = true;
$._isCollateralized = true;
}
// Remote contracts should only ever receive single-hop messages because
// multi-hop messages are always routed through the home contract.
if (transferrerMessage.messageType == TransferrerMessageType.SINGLE_HOP_SEND) {
SingleHopSendMessage memory payload =
abi.decode(transferrerMessage.payload, (SingleHopSendMessage));
_withdraw(payload.recipient, payload.amount);
} else if (transferrerMessage.messageType == TransferrerMessageType.SINGLE_HOP_CALL) {
// The {sourceBlockchainID}, and {originSenderAddress} specified in the message
// payload will not match the sender of this Teleporter message in the case of a
// multi-hop message. Since Teleporter messages are only received from the specified
// token TokenHome instance, no additional authentication is needed on the payload values.
SingleHopCallMessage memory payload =
abi.decode(transferrerMessage.payload, (SingleHopCallMessage));
_handleSendAndCall(payload, payload.amount);
} else {
revert("TokenRemote: invalid message type");
}
}TokenHomeコントラクトからクロスチェーンメッセージを受信した時のメインハンドラー関数。
Teleporterから呼び出されるエントリーポイントです。
まず、メッセージが登録済みのTokenHomeコントラクトから送られてきたことを検証します。
次に、_isRegisteredと_isCollateralizedフラグをtrueに更新します(このメッセージが届いたこと自体が、登録と担保の証明になるためです)。
メッセージのタイプを判別し、SINGLE_HOP_SENDであれば_withdraw(抽象関数)を、SINGLE_HOP_CALLであれば_handleSendAndCall(抽象関数)を呼び出して、これを継承するERC20TokenRemoteやNativeTokenRemoteに実際のトークン処理を任せます。
sequenceDiagram
participant TP as Teleporter
participant Self as TokenRemote
TP->>Self: _receiveTeleporterMessage(...)
Self->>Self: 送信元がTokenHomeであることを検証
Self->>Self: _isRegistered, _isCollateralized を true に更新
Self->>Self: message をデコード
alt messageType is SINGLE_HOP_SEND
Self->>Self: _withdraw(recipient, amount) (抽象)
else messageType is SINGLE_HOP_CALL
Self->>Self: _handleSendAndCall(payload, amount) (抽象)
else
Self->>Self: revert
end引数
sourceBlockchainIDメッセージの送信元チェーンID。originSenderAddressメッセージの送信元アドレス(TokenHomeコントラクトのアドレス)。messageエンコードされたTransferrerMessage。
_withdraw
/**
* @notice Withdraws tokens to the recipient address.
* @param recipient The address to withdraw tokens to
* @param amount The amount of tokens to withdraw
*/
function _withdraw(address recipient, uint256 amount) internal virtual;トークンをMint(発行)して受取人のアドレスに送付するための内部関数。
_receiveTeleporterMessageから呼び出されます。
この関数は具体的な実装を持たず、子コントラクトがアセットの種類に応じて、トークンをMint(発行)して指定されたrecipientに送付する処理を実装する必要があります。
引数
recipientトークンを受け取るアドレス。amountMint(発行)するトークンの量。
_burn
/**
* @notice Burns the user's tokens to initiate a token transfer.
* @param amount The amount of tokens to burn
* @return The amount of tokens burned, which is the amount to credit
* for the token transfer.
*/
function _burn(
uint256 amount
) internal virtual returns (uint256);送付を開始するためにユーザーのトークンをBurnするための内部関数。
送付処理の最初に呼び出されます。 この関数は具体的な実装を持たず、子コントラクトがアセットの種類に応じて、ユーザーが保有するトークンをBurnする処理を実装する必要があります。
引数
amountBurnするトークンの量。
戻り値
uint256実際にBurnされたトークンの量。
_handleSendAndCall
/**
* @notice Processes a send and call message by calling the recipient contract.
* @param message The send and call message include recipient calldata
* @param amount The amount of tokens to be sent to the recipient. This amount is assumed to be
* already scaled to the local denomination of this contract.
*/
function _handleSendAndCall(
SingleHopCallMessage memory message,
uint256 amount
) internal virtual;「送付とコントラクト呼び出し」メッセージを処理するための内部関数。
_receiveTeleporterMessageから呼び出されます。
この関数は具体的な実装を持たず、子コントラクトがアセットの種類に応じて、トークンをMint(発行)して指定された宛先コントラクトを呼び出す処理を実装する必要があります。
引数
message呼び出し先情報などを含むメッセージ構造体。amount利用可能なトークンの量。
_handleFees
/**
* @notice Handles fees sent to this contract for a token transfer.
* The fee is expected to be approved by the sender for this token transfer contract to use,
* and will be transferred to this contract to allocate for the token transfer.
* @param feeTokenAddress The address of the fee token
* @param feeAmount The amount of the fee
*/
function _handleFees(
address feeTokenAddress,
uint256 feeAmount
) internal virtual returns (uint256);Teleporterメッセージの手数料を処理するための内部関数。
registerWithHomeや_prepareSendなどから呼び出されます。
この関数は具体的な実装を持たず、子コントラクトが手数料として指定されたERC20トークンをユーザーからこのコントラクトへtransferFromする処理を実装する必要があります。
引数
feeTokenAddress手数料として使用するERC20トークンのアドレス。feeAmount手数料の額。
戻り値
uint256実際に確保された手数料の額。
_prepareSend
/**
* @dev Prepares tokens to be sent to another chain by handling the
* deposit, burning, and checking that the corresonding amount of
* home tokens is greater than zero.
*/
function _prepareSend(
uint256 amount,
address primaryFeeTokenAddress,
uint256 primaryFee,
uint256 secondaryFee
) private returns (uint256, uint256) {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
// Burn the amount of tokens that will be transferred.
amount = _burn(amount);
// Transfer the primary fee to pay for fees on the first hop.
// The user can specify this contract as {primaryFeeTokenAddress},
// in which case the fee will be paid on top of the transferred amount.
primaryFee = _handleFees(primaryFeeTokenAddress, primaryFee);
// The transferred amount must cover the secondary fee, because the secondary fee
// is directly subtracted from the transferred amount on the intermediate (home) chain
// performing the multi-hop, before forwarding to the final destination TokenRemote instance.
require(
TokenScalingUtils.removeTokenScale($._tokenMultiplier, $._multiplyOnRemote, amount)
> TokenScalingUtils.removeTokenScale(
$._tokenMultiplier, $._multiplyOnRemote, secondaryFee
),
"TokenRemote: insufficient tokens to transfer"
);
// Return the amount in this contract's local denomination and the primary fee.
return (amount, primaryFee);
}トークン送付の準備(Burnと手数料処理)を行う内部関数。
まず_burn(抽象関数)を呼び出してユーザーのトークンをBurnします。
次に_handleFees(抽象関数)を呼び出して、最初のホップの手数料をユーザーから確保します。
マルチホップの場合に備え、Burnしたトークン量が2番目のホップの手数料(secondaryFee)を上回っていることを、小数桁数をホームチェーン基準に換算した上で検証します。
sequenceDiagram
participant Caller as _processSend...
participant Self as TokenRemote
Caller->>Self: _prepareSend(...)
Self->>Self: _burn(amount) (抽象)
Self-->>Self: 実際にBurnされたamountを受け取る
Self->>Self: _handleFees(primaryFee) (抽象)
Self-->>Self: 実際に確保したprimaryFeeを受け取る
Self->>Self: amountがsecondaryFeeを上回るか検証
Self-->>Caller: amount, primaryFee を返す引数
amount送付するトークン量。primaryFeeTokenAddress最初のホップの手数料トークンのアドレス。primaryFee最初のホップの手数料額。secondaryFee2番目のホップの手数料額。
戻り値
uint256実際にBurnされたトークン量。uint256実際に確保された最初のホップの手数料額。
_processSend
/**
* @dev Sends tokens to the specified destination.
*/
function _processSend(SendTokensInput calldata input, uint256 amount) private {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
_validateSingleHopInput(
input.destinationTokenTransferrerAddress, input.secondaryFee, input.multiHopFallback
);
uint256 primaryFee;
(amount, primaryFee) = _prepareSend({
amount: amount,
primaryFeeTokenAddress: input.primaryFeeTokenAddress,
primaryFee: input.primaryFee,
secondaryFee: input.secondaryFee
});
TransferrerMessage memory message = TransferrerMessage({
messageType: TransferrerMessageType.SINGLE_HOP_SEND,
payload: abi.encode(SingleHopSendMessage({recipient: input.recipient, amount: amount}))
});
bytes32 messageID = _sendTeleporterMessage(
TeleporterMessageInput({
destinationBlockchainID: $._tokenHomeBlockchainID,
destinationAddress: $._tokenHomeAddress,
feeInfo: TeleporterFeeInfo({
feeTokenAddress: input.primaryFeeTokenAddress,
amount: primaryFee
}),
requiredGasLimit: input.requiredGasLimit,
allowedRelayerAddresses: new address[](0),
message: abi.encode(message)
})
);
emit TokensSent(messageID, _msgSender(), input, amount);
}シングルホップ(TokenHomeへ戻す)のトークン送付処理を行う内部関数。
_sendから呼び出されます。
まず_validateSingleHopInputで入力値を検証します。
_prepareSendでトークンのBurnと手数料処理を行った後、SINGLE_HOP_SENDタイプのメッセージを構築し、_sendTeleporterMessageでTokenHomeコントラクトへ送信します。
最後にTokensSentイベントを発行します。
sequenceDiagram
participant Caller as _send
participant Self as TokenRemote
participant TP as Teleporter
Caller->>Self: _processSend(input, amount)
Self->>Self: _validateSingleHopInput(input)
Self->>Self: _prepareSend(...)
Self-->>Self: amount, primaryFee を受け取る
Self->>Self: SingleHopSendMessage を構築
Self->>TP: _sendTeleporterMessage(...)
TP-->>Self: messageID を返す
Self->>Self: TokensSent イベントを発行引数
input送付先情報などを含むSendTokensInput構造体。amount送付するトークンの量。
_processSendMultiHop
/**
* @dev Sends tokens to the specified destination via multi-hop.
*/
function _processSendMultiHop(SendTokensInput calldata input, uint256 amount) private {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
_validateMultiHopInput(
input.destinationBlockchainID,
input.destinationTokenTransferrerAddress,
input.multiHopFallback
);
uint256 primaryFee;
(amount, primaryFee) = _prepareSend({
amount: amount,
primaryFeeTokenAddress: input.primaryFeeTokenAddress,
primaryFee: input.primaryFee,
secondaryFee: input.secondaryFee
});
TransferrerMessage memory message = TransferrerMessage({
messageType: TransferrerMessageType.MULTI_HOP_SEND,
payload: abi.encode(
MultiHopSendMessage({
destinationBlockchainID: input.destinationBlockchainID,
destinationTokenTransferrerAddress: input.destinationTokenTransferrerAddress,
recipient: input.recipient,
amount: amount,
secondaryFee: input.secondaryFee,
secondaryGasLimit: input.requiredGasLimit,
multiHopFallback: input.multiHopFallback
})
)
});
bytes32 messageID = _sendTeleporterMessage(
TeleporterMessageInput({
destinationBlockchainID: $._tokenHomeBlockchainID,
destinationAddress: $._tokenHomeAddress,
feeInfo: TeleporterFeeInfo({
feeTokenAddress: input.primaryFeeTokenAddress,
amount: primaryFee
}),
requiredGasLimit: MULTI_HOP_SEND_REQUIRED_GAS,
allowedRelayerAddresses: new address[](0),
message: abi.encode(message)
})
);
emit TokensSent(messageID, _msgSender(), input, amount);
}マルチホップ(他のリモートへ送る)のトークン送付処理を行う内部関数。
_sendから呼び出されます。
_validateMultiHopInputで入力値を検証し、_prepareSendでトークンのBurnと手数料処理を行います。
その後、MULTI_HOP_SENDタイプのメッセージを構築し、TokenHomeコントラクトへ送信します。
この時、ガスリミットには定数MULTI_HOP_SEND_REQUIRED_GASが使用されます。
最後にTokensSentイベントを発行します。
sequenceDiagram
participant Caller as _send
participant Self as TokenRemote
participant TP as Teleporter
Caller->>Self: _processSendMultiHop(input, amount)
Self->>Self: _validateMultiHopInput(...)
Self->>Self: _prepareSend(...)
Self-->>Self: amount, primaryFee を受け取る
Self->>Self: MultiHopSendMessage を構築
Self->>TP: _sendTeleporterMessage(...)
TP-->>Self: messageID を返す
Self->>Self: TokensSent イベントを発行引数
input送付先情報などを含むSendTokensInput構造体。amount送付するトークンの量。
_processSendAndCall
/**
* @dev Sends tokens to the specified recipient contract on the destination blockchain ID by
* calling the {receiveTokens} method of the respective recipient.
*/
function _processSendAndCall(SendAndCallInput calldata input, uint256 amount) private {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
_validateSingleHopInput(
input.destinationTokenTransferrerAddress, input.secondaryFee, input.multiHopFallback
);
uint256 primaryFee;
(amount, primaryFee) = _prepareSend({
amount: amount,
primaryFeeTokenAddress: input.primaryFeeTokenAddress,
primaryFee: input.primaryFee,
secondaryFee: input.secondaryFee
});
TransferrerMessage memory message = TransferrerMessage({
messageType: TransferrerMessageType.SINGLE_HOP_CALL,
payload: abi.encode(
SingleHopCallMessage({
sourceBlockchainID: $._blockchainID,
originTokenTransferrerAddress: address(this),
originSenderAddress: _msgSender(),
recipientContract: input.recipientContract,
amount: amount,
recipientPayload: input.recipientPayload,
recipientGasLimit: input.recipientGasLimit,
fallbackRecipient: input.fallbackRecipient
})
)
});
// Send message to the token TokenHome instance.
bytes32 messageID = _sendTeleporterMessage(
TeleporterMessageInput({
destinationBlockchainID: $._tokenHomeBlockchainID,
destinationAddress: $._tokenHomeAddress,
feeInfo: TeleporterFeeInfo({
feeTokenAddress: input.primaryFeeTokenAddress,
amount: primaryFee
}),
requiredGasLimit: input.requiredGasLimit,
allowedRelayerAddresses: new address[](0),
message: abi.encode(message)
})
);
emit TokensAndCallSent(messageID, _msgSender(), input, amount);
}シングルホップの「送付とコントラクト呼び出し」処理を行う内部関数。
_sendAndCallから呼び出されます。
入力値検証、_prepareSendでの準備は_processSendと同様です。
構築するメッセージがSINGLE_HOP_CALLタイプになり、送信元情報や宛先コントラクト情報など、より多くの情報を含みます。
メッセージ送信後、TokensAndCallSentイベントを発行します。
sequenceDiagram
participant Caller as _sendAndCall
participant Self as TokenRemote
participant TP as Teleporter
Caller->>Self: _processSendAndCall(input, amount)
Self->>Self: _validateSingleHopInput(...)
Self->>Self: _prepareSend(...)
Self-->>Self: amount, primaryFee を受け取る
Self->>Self: SingleHopCallMessage を構築
Self->>TP: _sendTeleporterMessage(...)
TP-->>Self: messageID を返す
Self->>Self: TokensAndCallSent イベントを発行引数
input宛先コントラクト情報などを含むSendAndCallInput構造体。amount送付するトークンの量。
_processSendAndCallMultiHop
/**
* @dev Sends tokens to the specified recipient contract on the destination blockchain ID by
* calling the {receiveTokens} method of the respective recipient.
*/
function _processSendAndCallMultiHop(SendAndCallInput calldata input, uint256 amount) private {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
_validateMultiHopInput(
input.destinationBlockchainID,
input.destinationTokenTransferrerAddress,
input.multiHopFallback
);
uint256 primaryFee;
(amount, primaryFee) = _prepareSend({
amount: amount,
primaryFeeTokenAddress: input.primaryFeeTokenAddress,
primaryFee: input.primaryFee,
secondaryFee: input.secondaryFee
});
TransferrerMessage memory message = TransferrerMessage({
messageType: TransferrerMessageType.MULTI_HOP_CALL,
payload: abi.encode(
MultiHopCallMessage({
originSenderAddress: _msgSender(),
destinationBlockchainID: input.destinationBlockchainID,
destinationTokenTransferrerAddress: input.destinationTokenTransferrerAddress,
recipientContract: input.recipientContract,
amount: amount,
recipientPayload: input.recipientPayload,
recipientGasLimit: input.recipientGasLimit,
fallbackRecipient: input.fallbackRecipient,
multiHopFallback: input.multiHopFallback,
secondaryRequiredGasLimit: input.requiredGasLimit,
secondaryFee: input.secondaryFee
})
)
});
// The required gas limit for the first message sent back to the TokenHome instance
// needs to account for the number of words in the payload. Each word uses additional
// gas to include in the message to the final destination chain.
uint256 messageRequiredGasLimit = MULTI_HOP_CALL_REQUIRED_GAS
+ (calculateNumWords(input.recipientPayload.length) * MULTI_HOP_CALL_GAS_PER_WORD);
// Send message to the token TokenHome instance
bytes32 messageID = _sendTeleporterMessage(
TeleporterMessageInput({
destinationBlockchainID: $._tokenHomeBlockchainID,
destinationAddress: $._tokenHomeAddress,
feeInfo: TeleporterFeeInfo({
feeTokenAddress: input.primaryFeeTokenAddress,
amount: primaryFee
}),
requiredGasLimit: messageRequiredGasLimit,
allowedRelayerAddresses: new address[](0),
message: abi.encode(message)
})
);
emit TokensAndCallSent(messageID, _msgSender(), input, amount);
}マルチホップの「送付とコントラクト呼び出し」処理を行う内部関数。
_sendAndCallから呼び出されます。
_validateMultiHopInputと_prepareSendで準備した後、MULTI_HOP_CALLタイプのメッセージを構築します。
このメッセージは、最終的な宛先情報、ペイロード、手数料など、マルチホップに必要な全ての情報を含みます。
TokenHomeへのメッセージ送信に必要なガスリミットは、ペイロードの長さに応じて動的に計算されます。
メッセージ送信後、TokensAndCallSentイベントを発行します。
sequenceDiagram
participant Caller as _sendAndCall
participant Self as TokenRemote
participant TP as Teleporter
Caller->>Self: _processSendAndCallMultiHop(input, amount)
Self->>Self: _validateMultiHopInput(...)
Self->>Self: _prepareSend(...)
Self-->>Self: amount, primaryFee を受け取る
Self->>Self: MultiHopCallMessage を構築
Self->>Self: messageRequiredGasLimit を計算
Self->>TP: _sendTeleporterMessage(...)
TP-->>Self: messageID を返す
Self->>Self: TokensAndCallSent イベントを発行引数
input宛先コントラクト情報などを含むSendAndCallInput構造体。amount送付するトークンの量。
_validateSingleHopInput
function _validateSingleHopInput(
address destinationTokenTransferrerAddress,
uint256 secondaryFee,
address multiHopFallback
) private view {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
require(
destinationTokenTransferrerAddress == $._tokenHomeAddress,
"TokenRemote: invalid destination token transferrer address"
);
require(secondaryFee == 0, "TokenRemote: non-zero secondary fee");
require(multiHopFallback == address(0), "TokenRemote: non-zero multi-hop fallback");
}シングルホップ送付の入力値を検証する内部関数。
シングルホップ送付(TokenHomeへ戻す)に特化した検証を行います。
宛先アドレスが登録済みの_tokenHomeAddressと一致すること、secondaryFeeが0であること、multiHopFallbackがゼロアドレスであることを確認します。
引数
destinationTokenTransferrerAddress宛先コントラクトアドレス。secondaryFee2番目のホップの手数料。multiHopFallbackマルチホップ失敗時のフォールバックアドレス。
_validateMultiHopInput
function _validateMultiHopInput(
bytes32 destinationBlockchainID,
address destinationTokenTransferrerAddress,
address multiHopFallback
) private view {
TokenRemoteStorage storage $ = _getTokenRemoteStorage();
// If the destination blockchain ID is this blockchain, the destination
// token transferrer address must be a different contract. This is a multi-hop case to
// a different token transfer contract on this chain.
if (destinationBlockchainID == $._blockchainID) {
require(
destinationTokenTransferrerAddress != address(this),
"TokenRemote: invalid destination token transferrer address"
);
}
require(multiHopFallback != address(0), "TokenRemote: zero multi-hop fallback");
}マルチホップ送付の入力値を検証する内部関数。
マルチホップ送付に特化した検証を行います。
multiHopFallbackがゼロアドレスでないことを確認します。
また、もし宛先が同じチェーン上である場合は、自分自身のアドレスでないことを確認します(自分から自分へのマルチホップは無効)。
引数
destinationBlockchainID最終的な宛先のチェーンID。destinationTokenTransferrerAddress最終的な宛先コントラクトのアドレス。multiHopFallbackマルチホップ失敗時のフォールバックアドレス。
_validateSendTokensInput
function _validateSendTokensInput(
SendTokensInput calldata input
) private pure {
require(input.recipient != address(0), "TokenRemote: zero recipient address");
require(input.requiredGasLimit > 0, "TokenRemote: zero required gas limit");
require(
input.destinationBlockchainID != bytes32(0),
"TokenRemote: zero destination blockchain ID"
);
require(
input.destinationTokenTransferrerAddress != address(0),
"TokenRemote: zero destination token transferrer address"
);
}通常のトークン送付(send)を安全に実行するために入力値を検証する内部関数。
send関数が呼び出された時に、その引数であるSendTokensInput構造体の内容が有効であるかを検証し、基本的な設定ミスによるトランザクションの失敗や資産の喪失を防ぎます。
-
宛先の検証
recipient最終的なトークンの受取人アドレスがゼロでないことを確認します。 ゼロアドレスへの送付はトークンの永久的な喪失を意味するため、これを防ぎます。destinationBlockchainID宛先チェーンのIDがゼロでないことを確認します。 これにより、メッセージが有効なブロックチェーンにルーティングされることが保証されます。destinationTokenTransferrerAddress宛先チェーン上のトークンコントラクト(TokenHomeまたは別のTokenRemote)のアドレスがゼロでないことを確認します。 メッセージを処理する有効なコントラクトが存在することを保証します。
-
ガスリミットの検証
requiredGasLimit宛先チェーンでTeleporterメッセージを実行するために必要なガスリミットが0より大きいことを確認します。 ガスリミットが0の場合、トランザクションは宛先で確実に失敗するため、無駄な送付を防ぎます。
引数
input検証対象のSendTokensInput構造体。
_validateSendAndCallInput
function _validateSendAndCallInput(
SendAndCallInput calldata input
) private pure {
require(
input.destinationBlockchainID != bytes32(0),
"TokenRemote: zero destination blockchain ID"
);
require(
input.destinationTokenTransferrerAddress != address(0),
"TokenRemote: zero destination token transferrer address"
);
require(
input.recipientContract != address(0), "TokenRemote: zero recipient contract address"
);
require(input.requiredGasLimit > 0, "TokenRemote: zero required gas limit");
require(input.recipientGasLimit > 0, "TokenRemote: zero recipient gas limit");
require(
input.recipientGasLimit < input.requiredGasLimit,
"TokenRemote: invalid recipient gas limit"
);
require(
input.fallbackRecipient != address(0), "TokenRemote: zero fallback recipient address"
);
}「送付とコントラクト呼び出し」の入力値を検証する内部関数。
sendAndCallを安全に実行するための、入力値に対する一連の事前チェックを行います。
-
宛先の検証
destinationBlockchainID宛先のチェーンIDがゼロでないことを確認します。destinationTokenTransferrerAddress宛先チェーン上のトークンコントラクトのアドレスがゼロでないことを確認します。recipientContract最終的に呼び出される宛先コントラクトのアドレスがゼロでないことを確認します。 これらのチェックは、トークンが意図しない場所や無効なアドレスに送付されるのを防ぎます。
-
ガスリミットの検証
requiredGasLimit> 0 Teleporterメッセージ全体を処理するために必要なガスリミットが0より大きいことを確認します。recipientGasLimit> 0 最終的な宛先コントラクトを呼び出すためのガスリミットが0より大きいことを確認します。recipientGasLimit<requiredGasLimit最も重要な検証の1つです。 宛先コントラクト用のガス (recipientGasLimit) は、メッセージ全体用のガス (requiredGasLimit) よりも必ず小さくなければなりません。 なぜなら、Teleporterのメッセンジャーコントラクト自体が、メッセージの受信、デコード、最終的な呼び出しの準備といった処理にガスを消費するためです。 この条件を満たさない場合、トランザクションは確実に失敗します。
-
フォールバックの検証
fallbackRecipient宛先コントラクトの呼び出しが失敗した場合に、送付されたトークンを受け取るためのフォールバックアドレスがゼロでないことを確認し、トークンの喪失を防ぎます。
引数
input検証対象のSendAndCallInput構造体。
