Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article explores Avalanche ICTT. The diagrams walk through each stage of the process so that readers without an engineering background can understand the overall system. For developers, the article also examines the underlying source code in detail.

For a more detailed treatment of Avalanche ICTT, see the following book.

ICTT overview

Avalanche Interchain Token Transfer (ICTT) is an application for transferring tokens between different L1 blockchains. A set of smart contracts deployed across multiple L1s implements the system, using ICM (Interchain Messaging) for cross-chain communication.

For more on ICM (Interchain Messaging), see the following resources.

ICTT consists of one TokenHome contract and one or more TokenRemote contracts.

The Home contract is deployed on the L1 where the original token exists (the Home chain) and manages that token. The TokenRemote contract is deployed on the destination L1 (the Remote chain) and represents a wrapped version of the token being transferred.

The original diagrams are retained below; their labels may be in Japanese.

ICTT overview

Contract architecture

The inheritance relationships between the contracts are shown below.

Contract inheritance structure

The TokenHome contract contains the core implementation, the functionality shared by ERC20 and native tokens, and the definitions of the required functions. The corresponding UpgradeableContract implementations that inherit TokenHome handle ERC20-specific and native-token-specific operations. The ERC20TokenHome and NativeTokenHome contracts inherit those implementations without further changes. Custom functionality can be added at that level.

Token transfers

A transfer locks tokens on the Home chain and issues new wrapped tokens on the Remote chain.

Transferring tokens from Home to Remote

  1. The user requests that the TokenHome contract be granted permission to transfer the tokens they hold.
  2. The permission to transfer the tokens is granted.
  3. The user requests a token transfer to the Remote chain.
  4. The tokens are locked in the TokenHome contract and transferred to the Remote chain.

The TokenHome contract tracks the token balances transferred to each TokenRemote contract across the L1s. When tokens are returned to TokenHome, the original tokens locked in that contract are released to the user.

Returning tokens to the Home chain

  1. The user requests that the tokens transferred to the Remote chain be returned.
  2. The tokens are transferred from the Remote chain to the Home chain.
  3. The locked tokens are returned to the user.

A TokenHome contract can handle either an ERC20 token or a native token and transfer it to any previously registered TokenRemote contract. Tokens on the Remote chain may also be ERC20 or native tokens, allowing the combinations of token types between Home and Remote chains illustrated below.

Supported ERC20 and native-token transfer combinations

Multi-hop transfers are also supported. For example, to transfer between two Remote chains whose TokenRemote contracts are connected to the same TokenHome contract, the first Remote chain's TokenRemote sends a request to TokenHome. Upon receiving the request, TokenHome transfers the tokens to the second Remote chain's TokenRemote contract.

Multi-hop token transfer

In addition to basic token transfers, ICTT provides a sendAndCall interface that combines token transfer and use of the tokens by a smart contract within a single ICM message. If the destination smart contract call fails, the transferred tokens are sent to a fallback address on the destination chain. The sendAndCall interface makes it possible to use transferred tokens directly in dApps on other chains, for example to execute swaps or pay service fees.

Transfer workflow

ICTT uses ICM. As a prerequisite, cross-chain communication passes through Teleporter, the Warp Precompile, and a Relayer, as described below. For the full ICM workflow, see the following article.

Contract deployment

First, deploy the following set of contracts.

Contract deployment

  • Home chain
    • TokenHome contract
    • ERC20 contract
  • Remote chain
    • TokenRemote contract

TokenHome contract

When deploying the TokenHome contract, supply the Teleporter contract information and the ERC20 contract address as shown below.

contracts/ictt/TokenHome/TokenHome.sol#L112-L124
        address teleporterRegistryAddress,
        address teleporterManager,
        uint256 minTeleporterVersion,
        address tokenAddress,
        uint8 tokenDecimals
    ) internal virtual onlyInitializing {
        __TeleporterRegistryOwnableApp_init(
            teleporterRegistryAddress, teleporterManager, minTeleporterVersion
        );
        __SendReentrancyGuard_init();
        __TokenHome_init_unchained(tokenAddress, tokenDecimals);
    }
ava-labs/icm-contractsの元のファイルを開く

teleporterRegistryAddress and teleporterManager refer to components used to manage versions of the Teleporter contract.

For more on the Teleporter contract, see the following resource.

When using a native token, supply the address of the contract for its wrapped version instead, as shown below.

contracts/ictt/TokenHome/NativeTokenHomeUpgradeable.sol#L80-L89
    function initialize(
        address teleporterRegistryAddress,
        address teleporterManager,
        uint256 minTeleporterVersion,
        address wrappedTokenAddress
    ) public initializer {
        __NativeTokenHome_init(
            teleporterRegistryAddress, teleporterManager, minTeleporterVersion, wrappedTokenAddress
        );
    }
ava-labs/icm-contractsの元のファイルを開く

This abstracts native-token handling by converting native tokens into wrapped tokens so they can be processed through the same workflow as ERC20 tokens.

TokenRemote contract

The ERC20 implementation of the TokenRemote contract inherits ERC20, so the ERC20 token name and symbol must be supplied at deployment.

contracts/ictt/TokenRemote/ERC20TokenRemoteUpgradeable.sol#L30
contract ERC20TokenRemoteUpgradeable is IERC20TokenTransferrer, ERC20Upgradeable, TokenRemote {
ava-labs/icm-contractsの元のファイルを開く

The ERC20 name and symbol are passed as tokenName and tokenSymbol below.

contracts/ictt/TokenRemote/ERC20TokenRemoteUpgradeable.sol#L78-L85
    function initialize(
        TokenRemoteSettings memory settings,
        string memory tokenName,
        string memory tokenSymbol,
        uint8 tokenDecimals
    ) public initializer {
        __ERC20TokenRemote_init(settings, tokenName, tokenSymbol, tokenDecimals);
    }
ava-labs/icm-contractsの元のファイルを開く

For native tokens, the native token itself is minted.

The TokenRemoteSettings also contains the Teleporter contract information, the Home chain ID, and the TokenHome contract address, as shown below. ICM (Interchain Messaging) requires this information.

contracts/ictt/TokenRemote/interfaces/ITokenRemote.sol#L22-L29
struct TokenRemoteSettings {
    address teleporterRegistryAddress;
    address teleporterManager;
    uint256 minTeleporterVersion;
    bytes32 tokenHomeBlockchainID;
    address tokenHomeAddress;
    uint8 tokenHomeDecimals;
}
ava-labs/icm-contractsの元のファイルを開く

Registering the Remote contract

The TokenHome contract does not initially contain the TokenRemote contract information, so the Remote contract must be registered in advance.

Registering a Remote contract on Home

On the TokenRemote side, the TokenHome contract is already registered when TokenRemote is deployed.

Home contract registration on Remote

Register the TokenRemote contract by calling registerWithHome.

contracts/ictt/TokenRemote/TokenRemote.sol#L207-L235
        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)
            })
        );
    }
ava-labs/icm-contractsの元のファイルを開く

When using ICM, cross-chain communication invokes the _receiveTeleporterMessage function shown below.

contracts/ictt/TokenHome/TokenHome.sol#L495-L595
        bytes32 sourceBlockchainID,
        address originSenderAddress,
        bytes memory message
    ) internal override {
        TokenHomeStorage storage $ = _getTokenHomeStorage();
        TransferrerMessage memory transferrerMessage = abi.decode(message, (TransferrerMessage));
        if (transferrerMessage.messageType == TransferrerMessageType.SINGLE_HOP_SEND) {
            SingleHopSendMessage memory payload =
                abi.decode(transferrerMessage.payload, (SingleHopSendMessage));

            uint256 homeAmount =
                _processSingleHopTransfer(sourceBlockchainID, originSenderAddress, payload.amount);

            // Send the tokens to the recipient.
            _withdraw(payload.recipient, homeAmount);
            return;
        } else if (transferrerMessage.messageType == TransferrerMessageType.SINGLE_HOP_CALL) {
            SingleHopCallMessage memory payload =
                abi.decode(transferrerMessage.payload, (SingleHopCallMessage));

            uint256 homeAmount =
                _processSingleHopTransfer(sourceBlockchainID, originSenderAddress, payload.amount);

            // Verify that the payload's source blockchain ID and origin token transferrer address matches the source blockchain ID
            // and origin sender address passed from Teleporter.
            require(
                payload.sourceBlockchainID == sourceBlockchainID,
                "TokenHome: mismatched source blockchain ID"
            );
            require(
                payload.originTokenTransferrerAddress == originSenderAddress,
                "TokenHome: mismatched origin sender address"
            );

            _handleSendAndCall(payload, homeAmount);
            return;
        } else if (transferrerMessage.messageType == TransferrerMessageType.MULTI_HOP_SEND) {
            MultiHopSendMessage memory payload =
                abi.decode(transferrerMessage.payload, (MultiHopSendMessage));

            (uint256 homeAmount, uint256 fee) = _processMultiHopTransfer(
                sourceBlockchainID, originSenderAddress, payload.amount, payload.secondaryFee
            );

            // For a multi-hop send, the fee token address has to be {tokenAddress},
            // because the fee is taken from the amount that has already been deposited.
            // For ERC20 tokens, the token address of the contract is directly passed.
            // For native assets, the contract address is the wrapped token contract.
            _routeMultiHop(
                SendTokensInput({
                    destinationBlockchainID: payload.destinationBlockchainID,
                    destinationTokenTransferrerAddress: payload.destinationTokenTransferrerAddress,
                    recipient: payload.recipient,
                    primaryFeeTokenAddress: $._tokenAddress,
                    primaryFee: fee,
                    secondaryFee: 0,
                    requiredGasLimit: payload.secondaryGasLimit,
                    multiHopFallback: payload.multiHopFallback
                }),
                homeAmount
            );
            return;
        } else if (transferrerMessage.messageType == TransferrerMessageType.MULTI_HOP_CALL) {
            MultiHopCallMessage memory payload =
                abi.decode(transferrerMessage.payload, (MultiHopCallMessage));

            (uint256 homeAmount, uint256 fee) = _processMultiHopTransfer(
                sourceBlockchainID, originSenderAddress, payload.amount, payload.secondaryFee
            );

            // For a multi-hop send, the fee token address has to be {tokenAddress},
            // because the fee is taken from the amount that has already been deposited.
            // For ERC20 tokens, the token address of the contract is directly passed.
            // For native assets, the contract address is the wrapped token contract.
            _routeMultiHopSendAndCall({
                sourceBlockchainID: sourceBlockchainID,
                originTokenTransferrerAddress: originSenderAddress,
                originSenderAddress: payload.originSenderAddress,
                input: SendAndCallInput({
                    destinationBlockchainID: payload.destinationBlockchainID,
                    destinationTokenTransferrerAddress: payload.destinationTokenTransferrerAddress,
                    recipientContract: payload.recipientContract,
                    recipientPayload: payload.recipientPayload,
                    requiredGasLimit: payload.secondaryRequiredGasLimit,
                    recipientGasLimit: payload.recipientGasLimit,
                    multiHopFallback: payload.multiHopFallback,
                    fallbackRecipient: payload.fallbackRecipient,
                    primaryFeeTokenAddress: $._tokenAddress,
                    primaryFee: fee,
                    secondaryFee: 0
                }),
                amount: homeAmount
            });
            return;
        } else if (transferrerMessage.messageType == TransferrerMessageType.REGISTER_REMOTE) {
            RegisterRemoteMessage memory payload =
                abi.decode(transferrerMessage.payload, (RegisterRemoteMessage));
            _registerRemote(sourceBlockchainID, originSenderAddress, payload);
        }
    }
ava-labs/icm-contractsの元のファイルを開く

The implementation branches according to the received message type (in this case, REGISTER_REMOTE). When registering a TokenRemote contract with TokenHome, the _registerRemote function runs. Its arguments include the source L1 chain ID and the source contract address (the TokenRemote contract).

contracts/ictt/TokenHome/TokenHome.sol#L590-L594
            RegisterRemoteMessage memory payload =
                abi.decode(transferrerMessage.payload, (RegisterRemoteMessage));
            _registerRemote(sourceBlockchainID, originSenderAddress, payload);
        }
    }
ava-labs/icm-contractsの元のファイルを開く

After performing several validation checks, _registerRemote registers the TokenRemote contract. It also accounts for differences in the number of decimals used by the ERC20 tokens.

contracts/ictt/TokenHome/TokenHome.sol#L170-L225
        bytes32 remoteBlockchainID,
        address remoteTokenTransferrerAddress,
        RegisterRemoteMessage memory message
    ) internal {
        TokenHomeStorage storage $ = _getTokenHomeStorage();
        require(remoteBlockchainID != bytes32(0), "TokenHome: zero remote blockchain ID");
        require(
            remoteBlockchainID != $._blockchainID, "TokenHome: cannot register remote on same chain"
        );
        require(
            remoteTokenTransferrerAddress != address(0),
            "TokenHome: zero remote token transferrer address"
        );
        require(
            !$._registeredRemotes[remoteBlockchainID][remoteTokenTransferrerAddress].registered,
            "TokenHome: remote already registered"
        );
        require(
            message.remoteTokenDecimals <= TokenScalingUtils.MAX_TOKEN_DECIMALS,
            "TokenHome: remote token decimals too high"
        );
        require(
            message.homeTokenDecimals == $._tokenDecimals, "TokenHome: invalid home token decimals"
        );

        (uint256 tokenMultiplier, bool multiplyOnRemote) = TokenScalingUtils
            .deriveTokenMultiplierValues($._tokenDecimals, message.remoteTokenDecimals);

        // Calculate the collateral needed in home token denomination.
        uint256 collateralNeeded = TokenScalingUtils.removeTokenScale(
            tokenMultiplier, multiplyOnRemote, message.initialReserveImbalance
        );

        // Round up the collateral needed by 1 in the case that {multiplyOnRemote} is true and
        // {initialReserveImbalance} is not divisible by the {tokenMultiplier} to
        // ensure that the full amount is accounted for.
        if (multiplyOnRemote && message.initialReserveImbalance % tokenMultiplier != 0) {
            collateralNeeded += 1;
        }

        $._registeredRemotes[remoteBlockchainID][remoteTokenTransferrerAddress] =
        RemoteTokenTransferrerSettings({
            registered: true,
            collateralNeeded: collateralNeeded,
            tokenMultiplier: tokenMultiplier,
            multiplyOnRemote: multiplyOnRemote
        });

        emit RemoteRegistered(
            remoteBlockchainID,
            remoteTokenTransferrerAddress,
            collateralNeeded,
            message.remoteTokenDecimals
        );
    }
ava-labs/icm-contractsの元のファイルを開く

Providing collateral

Providing collateral

When deploying a TokenRemote contract, you can specify a value called initialReserveImbalance_. This value specifies the initial amount of tokens issued.

contracts/ictt/TokenRemote/TokenRemote.sol#L151-L163
        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);
    }
ava-labs/icm-contractsの元のファイルを開く

The specified value is passed along when the TokenRemote contract registers with TokenHome.

contracts/ictt/TokenRemote/TokenRemote.sol#L215
            homeTokenDecimals: $._homeTokenDecimals,
ava-labs/icm-contractsの元のファイルを開く

On the TokenHome side, _addCollateral is executed. Depositing the specified amount of the ERC20 token associated with TokenHome as collateral satisfies the initial issuance requirement.

contracts/ictt/TokenHome/TokenHome.sol#L449-L486
        bytes32 remoteBlockchainID,
        address remoteTokenTransferrerAddress,
        uint256 amount
    ) internal sendNonReentrant {
        TokenHomeStorage storage $ = _getTokenHomeStorage();
        RemoteTokenTransferrerSettings memory remoteSettings =
            $._registeredRemotes[remoteBlockchainID][remoteTokenTransferrerAddress];
        require(remoteSettings.registered, "TokenHome: remote not registered");
        require(remoteSettings.collateralNeeded > 0, "TokenHome: zero collateral needed");

        // Deposit the full amount, and withdraw back to the sender if there is excess.
        amount = _deposit(amount);

        // Calculate the remaining collateral needed, any excess amount, and adjust
        // {amount} to represent the amount of tokens added as collateral.
        uint256 remainingCollateralNeeded;
        uint256 excessAmount;
        if (amount >= remoteSettings.collateralNeeded) {
            remainingCollateralNeeded = 0;
            excessAmount = amount - remoteSettings.collateralNeeded;
            amount = remoteSettings.collateralNeeded;
        } else {
            remainingCollateralNeeded = remoteSettings.collateralNeeded - amount;
        }

        // Update the remaining collateral needed.
        $._registeredRemotes[remoteBlockchainID][remoteTokenTransferrerAddress].collateralNeeded =
            remainingCollateralNeeded;
        emit CollateralAdded(
            remoteBlockchainID, remoteTokenTransferrerAddress, amount, remainingCollateralNeeded
        );

        // If there is excess amount, send it back to the sender.
        if (excessAmount > 0) {
            _withdraw(_msgSender(), excessAmount);
        }
    }
ava-labs/icm-contractsの元のファイルを開く

The original article describes collateralNeeded being true as indicating that the initial issuance has been collateralized. See the linked implementation for the actual condition.

contracts/ictt/TokenHome/TokenHome.sol#L476-L477
            remainingCollateralNeeded;
        emit CollateralAdded(
ava-labs/icm-contractsの元のファイルを開く

When the TokenHome contract sends a request to issue tokens on the Remote chain (through the TokenRemote contract), it checks collateralNeeded as shown below.

contracts/ictt/TokenHome/TokenHome.sol#L766
ava-labs/icm-contractsの元のファイルを開く

Users therefore cannot transfer tokens to the relevant Remote chain until the initial issuance has been covered.

You can also specify 0, which indicates that there is no initial issuance. In this case, users can transfer tokens to the Remote chain immediately after the TokenRemote contract is deployed.

Approval

To transfer ERC20 tokens from the Home chain to the Remote chain, the user must first approve the TokenHome contract to spend the transfer amount of its associated ERC20 token. This approve allows the TokenHome contract to transfer (transferFrom) the user's funds on their behalf.

Native-token transfers do not require approve.

Executing a transfer

The user submits a request to transfer ERC20 tokens from the Home chain to the Remote chain.

Native-token transfers follow almost the same workflow.

Home chain

Call the send function on the TokenHome contract.

contracts/ictt/TokenHome/ERC20TokenHomeUpgradeable.sol#L122-L124
    function send(SendTokensInput calldata input, uint256 amount) external {
        _send(input, amount);
    }
ava-labs/icm-contractsの元のファイルを開く

This invokes the internal _send function.

contracts/ictt/TokenHome/TokenHome.sol#L240-L276
        _validateSendTokensInput(input);
        // Require that a single hop transfer does not have a multi-hop fallback recipient.
        require(input.multiHopFallback == address(0), "TokenHome: non-zero multi-hop fallback");

        (uint256 adjustedAmount, uint256 feeAmount) = _prepareSend({
            remoteBlockchainID: input.destinationBlockchainID,
            remoteTokenTransferrerAddress: input.destinationTokenTransferrerAddress,
            amount: amount,
            primaryFeeTokenAddress: input.primaryFeeTokenAddress,
            feeAmount: input.primaryFee
        });

        TransferrerMessage memory message = TransferrerMessage({
            messageType: TransferrerMessageType.SINGLE_HOP_SEND,
            payload: abi.encode(
                SingleHopSendMessage({recipient: input.recipient, amount: adjustedAmount})
            )
        });

        // Send message to the TokenRemote instance
        bytes32 messageID = _sendTeleporterMessage(
            TeleporterMessageInput({
                destinationBlockchainID: input.destinationBlockchainID,
                destinationAddress: input.destinationTokenTransferrerAddress,
                feeInfo: TeleporterFeeInfo({
                    feeTokenAddress: input.primaryFeeTokenAddress,
                    amount: feeAmount
                }),
                requiredGasLimit: input.requiredGasLimit,
                allowedRelayerAddresses: new address[](0),
                message: abi.encode(message)
            })
        );

        emit TokensSent(messageID, _msgSender(), input, adjustedAmount);
    }
ava-labs/icm-contractsの元のファイルを開く

After checking the execution conditions, _prepareSend transfers the ERC20 tokens to the TokenHome contract and locks them there.

contracts/ictt/TokenHome/TokenHome.sol#L755-L788
        bytes32 remoteBlockchainID,
        address remoteTokenTransferrerAddress,
        uint256 amount,
        address primaryFeeTokenAddress,
        uint256 feeAmount
    ) private returns (uint256, uint256) {
        TokenHomeStorage storage $ = _getTokenHomeStorage();
        RemoteTokenTransferrerSettings memory remoteSettings =
            $._registeredRemotes[remoteBlockchainID][remoteTokenTransferrerAddress];
        require(remoteSettings.registered, "TokenHome: remote not registered");
        require(remoteSettings.collateralNeeded == 0, "TokenHome: collateral needed for remote");

        // Deposit the funds sent from the user to the token transferrer,
        // and set to adjusted amount after deposit.
        amount = _deposit(amount);

        if (feeAmount > 0) {
            feeAmount = SafeERC20TransferFrom.safeTransferFrom(
                IERC20(primaryFeeTokenAddress), _msgSender(), feeAmount
            );
        }

        // Scale the amount based on the token multiplier for the given TokenRemote instance.
        uint256 scaledAmount = TokenScalingUtils.applyTokenScale(
            remoteSettings.tokenMultiplier, remoteSettings.multiplyOnRemote, amount
        );
        require(scaledAmount > 0, "TokenHome: zero scaled amount");

        // Increase the balance of the TokenRemote instance by the scaled amount.
        $._transferredBalances[remoteBlockchainID][remoteTokenTransferrerAddress] += scaledAmount;

        return (scaledAmount, feeAmount);
    }
ava-labs/icm-contractsの元のファイルを開く

The safeTransferFrom function used here is implemented in a library called SafeERC20TransferFrom. It transfers the token amount from the address specified by from (the user's address) to address(this) (the TokenHome contract), using the amount specified by amount.

contracts/utilities/SafeERC20TransferFrom.sol#L46-L60
    function safeTransferFrom(
        IERC20 erc20,
        address from,
        uint256 amount
    ) internal returns (uint256) {
        uint256 balanceBefore = erc20.balanceOf(address(this));
        erc20.safeTransferFrom(from, address(this), amount);
        uint256 balanceAfter = erc20.balanceOf(address(this));

        require(balanceAfter > balanceBefore, "SafeERC20TransferFrom: balance not increased");

        return balanceAfter - balanceBefore;
    }
    // solhint-enable private-vars-leading-underscore
}
ava-labs/icm-contractsの元のファイルを開く

The request is then sent to the Remote chain through the Teleporter contract.

contracts/ictt/TokenHome/TokenHome.sol#L261-L273
            TeleporterMessageInput({
                destinationBlockchainID: input.destinationBlockchainID,
                destinationAddress: input.destinationTokenTransferrerAddress,
                feeInfo: TeleporterFeeInfo({
                    feeTokenAddress: input.primaryFeeTokenAddress,
                    amount: feeAmount
                }),
                requiredGasLimit: input.requiredGasLimit,
                allowedRelayerAddresses: new address[](0),
                message: abi.encode(message)
            })
        );
ava-labs/icm-contractsの元のファイルを開く

The message type is set to SINGLE_HOP_SEND as shown below, allowing the Remote chain to identify the type of request.

contracts/ictt/TokenHome/TokenHome.sol#L253-L258
            messageType: TransferrerMessageType.SINGLE_HOP_SEND,
            payload: abi.encode(
                SingleHopSendMessage({recipient: input.recipient, amount: adjustedAmount})
            )
        });
ava-labs/icm-contractsの元のファイルを開く

Remote chain

ICM invokes _receiveTeleporterMessage on the designated contract on the destination chain.

contracts/ictt/TokenRemote/TokenRemote.sol#L329-L368
        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");
        }
    }
ava-labs/icm-contractsの元のファイルを開く

Because SINGLE_HOP_SEND is specified, the _withdraw function is called as shown below.

contracts/ictt/TokenRemote/TokenRemote.sol#L353-L356
            SingleHopSendMessage memory payload =
                abi.decode(transferrerMessage.payload, (SingleHopSendMessage));
            _withdraw(payload.recipient, payload.amount);
        } else if (transferrerMessage.messageType == TransferrerMessageType.SINGLE_HOP_CALL) {
ava-labs/icm-contractsの元のファイルを開く

The _withdraw function calls _mint to deliver the specified amount of ERC20 tokens to the designated address (recipient), using the amount specified by amount.

contracts/ictt/TokenRemote/ERC20TokenRemoteUpgradeable.sol#L136-L139
    function _withdraw(address recipient, uint256 amount) internal virtual override {
        emit TokensWithdrawn(recipient, amount);
        _mint(recipient, amount);
    }
ava-labs/icm-contractsの元のファイルを開く

The diagram below includes the Teleporter contract and Relayer.

Remote-chain transfer including Teleporter and Relayer

For a detailed explanation of the ICM workflow, see the following article.

Returning tokens

Consider the workflow for converting ERC20 tokens on a Remote chain back into ERC20 tokens on the Home chain.

The function to call is send, just as on the TokenHome contract.

contracts/ictt/TokenRemote/ERC20TokenRemoteUpgradeable.sol#L114-L116
    function send(SendTokensInput calldata input, uint256 amount) external {
        _send(input, amount);
    }
ava-labs/icm-contractsの元のファイルを開く

The internal _send function is called. For the relevant destination L1, it calls _processSend.

contracts/ictt/TokenRemote/TokenRemote.sol#L291-L299
        TokenRemoteStorage storage $ = _getTokenRemoteStorage();
        _validateSendTokensInput(input);
        if (input.destinationBlockchainID == $._tokenHomeBlockchainID) {
            _processSend(input, amount);
        } else {
            _processSendMultiHop(input, amount);
        }
    }
ava-labs/icm-contractsの元のファイルを開く

After checking execution conditions, the contract uses ICM to send a message to the TokenHome contract on the Home chain.

contracts/ictt/TokenRemote/TokenRemote.sol#L449-L483
        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);
    }
ava-labs/icm-contractsの元のファイルを開く

On TokenHome, the Teleporter contract calls _receiveTeleporterMessage. Because the message type is SINGLE_HOP_SEND, the following processing takes place.

contracts/ictt/TokenHome/TokenHome.sol#L495-L512
        bytes32 sourceBlockchainID,
        address originSenderAddress,
        bytes memory message
    ) internal override {
        TokenHomeStorage storage $ = _getTokenHomeStorage();
        TransferrerMessage memory transferrerMessage = abi.decode(message, (TransferrerMessage));
        if (transferrerMessage.messageType == TransferrerMessageType.SINGLE_HOP_SEND) {
            SingleHopSendMessage memory payload =
                abi.decode(transferrerMessage.payload, (SingleHopSendMessage));

            uint256 homeAmount =
                _processSingleHopTransfer(sourceBlockchainID, originSenderAddress, payload.amount);

            // Send the tokens to the recipient.
            _withdraw(payload.recipient, homeAmount);
            return;
        } else if (transferrerMessage.messageType == TransferrerMessageType.SINGLE_HOP_CALL) {
            SingleHopCallMessage memory payload =
ava-labs/icm-contractsの元のファイルを開く

Internally, the _withdraw function delivers the specified ERC20 token amount to the requesting user's address (recipient), using the amount specified by amount.

contracts/ictt/TokenHome/ERC20TokenHomeUpgradeable.sol#L163-L167
    function _withdraw(address recipient, uint256 amount) internal virtual override {
        ERC20TokenHomeStorage storage $ = _getERC20TokenHomeStorage();
        emit TokensWithdrawn(recipient, amount);
        $._token.safeTransfer(recipient, amount);
    }
ava-labs/icm-contractsの元のファイルを開く

This is the reverse of issuing tokens through the TokenHome contract.

Returning tokens

Executing additional logic

A token transfer can also execute arbitrary additional logic. To do this, call the sendAndCall function below. Pass the information about the operation you want to execute, such as calling a specific function on a specific Remote-chain contract, through the input argument.

contracts/ictt/TokenHome/ERC20TokenHomeUpgradeable.sol#L129-L137
    function sendAndCall(SendAndCallInput calldata input, uint256 amount) external {
        _sendAndCall({
            sourceBlockchainID: getBlockchainID(),
            originTokenTransferrerAddress: address(this),
            originSenderAddress: _msgSender(),
            input: input,
            amount: amount
        });
    }
ava-labs/icm-contractsの元のファイルを開く

The input argument stores the following SendAndCallInput information. Supply the target contract address as recipientContract and the byte-encoded execution information as recipientPayload.

contracts/ictt/interfaces/ITokenTransferrer.sol#L64-L76
struct SendAndCallInput {
    bytes32 destinationBlockchainID;
    address destinationTokenTransferrerAddress;
    address recipientContract;
    bytes recipientPayload;
    uint256 requiredGasLimit;
    uint256 recipientGasLimit;
    address multiHopFallback;
    address fallbackRecipient;
    address primaryFeeTokenAddress;
    uint256 primaryFee;
    uint256 secondaryFee;
}
ava-labs/icm-contractsの元のファイルを開く

On the Remote chain, the TokenRemote contract's _receiveTeleporterMessage function invokes the handler for the SINGLE_HOP_CALL message type (the _handleSendAndCall function).

contracts/ictt/TokenRemote/TokenRemote.sol#L357-L368
            // 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");
        }
    }
ava-labs/icm-contractsの元のファイルを開く

Inside _handleSendAndCall, additional logic is executed after the tokens have been issued, as shown below.

contracts/ictt/TokenRemote/ERC20TokenRemoteUpgradeable.sol#L192-L194
        bool success = CallUtils._callWithExactGas(
            message.recipientGasLimit, message.recipientContract, payload
        );
ava-labs/icm-contractsの元のファイルを開く

When sending the request from a Remote chain's TokenRemote contract, call sendAndCall in the same way.

contracts/ictt/TokenRemote/ERC20TokenRemoteUpgradeable.sol#L121-L123
    function sendAndCall(SendAndCallInput calldata input, uint256 amount) external {
        _sendAndCall(input, amount);
    }
ava-labs/icm-contractsの元のファイルを開く

As shown below, the workflow adds one operation to the basic token-transfer workflow.

Executing additional logic

Multi-hop transfers

Consider the workflow for transferring ERC20 tokens between two Remote chains.

First, call the send function on the first Remote chain's TokenRemote contract.

contracts/ictt/TokenRemote/ERC20TokenRemoteUpgradeable.sol#L114-L116
    function send(SendTokensInput calldata input, uint256 amount) external {
        _send(input, amount);
    }
ava-labs/icm-contractsの元のファイルを開く

In the input argument, set destinationBlockchainID to the chain ID of the other Remote chain. Set destinationTokenTransferrerAddress to the address of its TokenRemote contract.

contracts/ictt/interfaces/ITokenTransferrer.sol#L33-L42
struct SendTokensInput {
    bytes32 destinationBlockchainID;
    address destinationTokenTransferrerAddress;
    address recipient;
    address primaryFeeTokenAddress;
    uint256 primaryFee;
    uint256 secondaryFee;
    uint256 requiredGasLimit;
    address multiHopFallback;
}
ava-labs/icm-contractsの元のファイルを開く

Inside _send, the previously registered Home chain ID differs from the value of input.destinationBlockchainID supplied in the argument. The contract therefore identifies the request as a multi-hop transfer and invokes _processSendMultiHop.

contracts/ictt/TokenRemote/TokenRemote.sol#L291-L299
        TokenRemoteStorage storage $ = _getTokenRemoteStorage();
        _validateSendTokensInput(input);
        if (input.destinationBlockchainID == $._tokenHomeBlockchainID) {
            _processSend(input, amount);
        } else {
            _processSendMultiHop(input, amount);
        }
    }
ava-labs/icm-contractsの元のファイルを開く

The ICM message is addressed to the previously registered TokenHome contract on the Home chain. TokenHome acts as a hub, forwarding transfer requests between Remote chains.

contracts/ictt/TokenRemote/TokenRemote.sol#L488-L534
        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);
    }
ava-labs/icm-contractsの元のファイルを開く

On the Home chain, the Teleporter contract calls the _receiveTeleporterMessage function on TokenHome. In this example, the message type is MULTI_HOP_CALL, so the following processing takes place.

contracts/ictt/TokenHome/TokenHome.sol#L558-L590
            MultiHopCallMessage memory payload =
                abi.decode(transferrerMessage.payload, (MultiHopCallMessage));

            (uint256 homeAmount, uint256 fee) = _processMultiHopTransfer(
                sourceBlockchainID, originSenderAddress, payload.amount, payload.secondaryFee
            );

            // For a multi-hop send, the fee token address has to be {tokenAddress},
            // because the fee is taken from the amount that has already been deposited.
            // For ERC20 tokens, the token address of the contract is directly passed.
            // For native assets, the contract address is the wrapped token contract.
            _routeMultiHopSendAndCall({
                sourceBlockchainID: sourceBlockchainID,
                originTokenTransferrerAddress: originSenderAddress,
                originSenderAddress: payload.originSenderAddress,
                input: SendAndCallInput({
                    destinationBlockchainID: payload.destinationBlockchainID,
                    destinationTokenTransferrerAddress: payload.destinationTokenTransferrerAddress,
                    recipientContract: payload.recipientContract,
                    recipientPayload: payload.recipientPayload,
                    requiredGasLimit: payload.secondaryRequiredGasLimit,
                    recipientGasLimit: payload.recipientGasLimit,
                    multiHopFallback: payload.multiHopFallback,
                    fallbackRecipient: payload.fallbackRecipient,
                    primaryFeeTokenAddress: $._tokenAddress,
                    primaryFee: fee,
                    secondaryFee: 0
                }),
                amount: homeAmount
            });
            return;
        } else if (transferrerMessage.messageType == TransferrerMessageType.REGISTER_REMOTE) {
            RegisterRemoteMessage memory payload =
ava-labs/icm-contractsの元のファイルを開く

The internal _routeMultiHopSendAndCall function is invoked.

contracts/ictt/TokenHome/TokenHome.sol#L390-L444
        bytes32 sourceBlockchainID,
        address originTokenTransferrerAddress,
        address originSenderAddress,
        SendAndCallInput memory input,
        uint256 amount
    ) internal sendNonReentrant {
        _validateSendAndCallInput(input);
        uint256 adjustedAmount = _prepareMultiHopRouting(
            input.destinationBlockchainID,
            input.destinationTokenTransferrerAddress,
            amount,
            input.primaryFee
        );

        if (adjustedAmount == 0) {
            // If the adjusted amount is zero for any reason (i.e. unregistered remote,
            // being scaled down to zero, etc.), send the tokens to the multi-hop fallback recipient.
            _withdraw(input.multiHopFallback, amount);
            return;
        }

        TransferrerMessage memory message = TransferrerMessage({
            messageType: TransferrerMessageType.SINGLE_HOP_CALL,
            payload: abi.encode(
                SingleHopCallMessage({
                    sourceBlockchainID: sourceBlockchainID,
                    originTokenTransferrerAddress: originTokenTransferrerAddress,
                    originSenderAddress: originSenderAddress,
                    recipientContract: input.recipientContract,
                    amount: adjustedAmount,
                    recipientPayload: input.recipientPayload,
                    recipientGasLimit: input.recipientGasLimit,
                    fallbackRecipient: input.fallbackRecipient
                })
            )
        });

        // Send message to the TokenRemote instance.
        bytes32 messageID = _sendTeleporterMessage(
            TeleporterMessageInput({
                destinationBlockchainID: input.destinationBlockchainID,
                destinationAddress: input.destinationTokenTransferrerAddress,
                feeInfo: TeleporterFeeInfo({
                    feeTokenAddress: input.primaryFeeTokenAddress,
                    amount: input.primaryFee
                }),
                requiredGasLimit: input.requiredGasLimit,
                allowedRelayerAddresses: new address[](0),
                message: abi.encode(message)
            })
        );

        emit TokensAndCallRouted(messageID, input, adjustedAmount);
    }
ava-labs/icm-contractsの元のファイルを開く

Using the supplied information, the request is forwarded to the TokenRemote contract on the other Remote chain.

contracts/ictt/TokenHome/TokenHome.sol#L429-L441
            TeleporterMessageInput({
                destinationBlockchainID: input.destinationBlockchainID,
                destinationAddress: input.destinationTokenTransferrerAddress,
                feeInfo: TeleporterFeeInfo({
                    feeTokenAddress: input.primaryFeeTokenAddress,
                    amount: input.primaryFee
                }),
                requiredGasLimit: input.requiredGasLimit,
                allowedRelayerAddresses: new address[](0),
                message: abi.encode(message)
            })
        );
ava-labs/icm-contractsの元のファイルを開く

From this point, the workflow is the same as a normal request from TokenHome to TokenRemote. Routing transfers through TokenHome allows each TokenRemote contract to issue tokens based on TokenHome.

The workflow is illustrated below.

Multi-hop transfer workflow

Conclusion

This article covered Avalanche ICTT.

I also write about other technical topics, which you can explore through the following resources.

https://chaldene.net/

https://twitter.com/cardene777

https://cardene.substack.com/