Skip to content
Verified contractExactAGPL-3.0-only

CircleCCTPV2Gateway

Address0x50ec7edb30bf394ccfc748b895ba23a6777b7502
Balance

0 ETH

 

Transactions

19

 

Compiler

solc 0.8.22

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.22+commit.4fc1097e
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
AGPL-3.0-only
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
21,987,431
Creation transaction
0xcc90b306b0…e990f4b247

contracts/crosschain/circle-cctp-v2/CircleCCTPV2Gateway.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

import { ReentrancyGuard } from '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import { IActionDataStructures } from '../../interfaces/IActionDataStructures.sol';
import { IGateway } from '../interfaces/IGateway.sol';
import { IGatewayClient } from '../interfaces/IGatewayClient.sol';
import { ITokenDecimals } from '../../interfaces/ITokenDecimals.sol';
import { GatewayBase } from '../GatewayBase.sol';
import { SystemVersionId } from '../../SystemVersionId.sol';
import './helpers/CCTPV2MessageHelper.sol' as CCTPV2MessageHelper;
import '../../helpers/AddressHelper.sol' as AddressHelper;
import '../../helpers/GasReserveHelper.sol' as GasReserveHelper;
import '../../helpers/TransferHelper.sol' as TransferHelper;
import '../../Constants.sol' as Constants;
import '../../DataStructures.sol' as DataStructures;

/**
 * @title CircleCCTPV2Gateway
 * @notice The contract implementing the cross-chain messaging logic specific to Circle CCTP V2
 */
contract CircleCCTPV2Gateway is SystemVersionId, GatewayBase {
    /**
     * @notice Type-to-addresses structure for asset data values
     * @dev Is used as an array parameter item for multiple settings
     * @param assetType Asset type
     * @param assetAddress Asset address
     */
    struct AssetDataItem {
        uint256 assetType;
        address assetAddress;
    }

    /**
     * @notice Chain domain structure
     * @dev See https://developers.circle.com/stablecoins/supported-domains
     * @param chainId The EVM chain ID
     * @param domain The CCTP domain
     */
    struct ChainDomain {
        uint256 chainId;
        uint32 domain;
    }

    /**
     * @dev cctpTokenMessengerV2 The CCTP V2 token messenger address
     */
    ITokenMessengerV2 public cctpTokenMessengerV2;

    /**
     * @dev cctpMessageTransmitterV2 The CCTP V2 message transmitter address
     */
    IMessageTransmitterV2 public cctpMessageTransmitterV2;

    /**
     * @dev Registered asset types
     */
    uint256[] public assetTypeList;

    /**
     * @dev Registered asset type indices
     */
    mapping(uint256 assetType => DataStructures.OptionalValue assetTypeIndex)
        public assetTypeIndexMap;

    /**
     * @dev Registered asset addresses by asset type
     */
    mapping(uint256 assetType => address assetAddress) public assetMap;

    /**
     * @dev Registered asset flags by address
     */
    mapping(address account => bool isAsset) public isAssetAddress;

    /**
     * @dev Chain id to CCTP domain
     */
    mapping(uint256 chainId => DataStructures.OptionalValue domain) public chainIdToDomain;

    /**
     * @dev CCTP domain to chain id
     */
    mapping(uint32 domain => uint256 chainId) public domainToChainId;

    /**
     * @dev The address of the processing fee collector
     */
    address public processingFeeCollector;

    /**
     * @dev Target executor address flags
     */
    mapping(address account => bool flag) public isTargetExecutor;

    /**
     * @notice Emitted when the cross-chain endpoint contract references are set
     * @param cctpTokenMessengerV2 The token messenger contract reference
     * @param cctpMessageTransmitterV2 The message transmitter contract reference
     */
    event SetEndpoints(
        ITokenMessengerV2 indexed cctpTokenMessengerV2,
        IMessageTransmitterV2 indexed cctpMessageTransmitterV2
    );

    /**
     * @notice Emitted when the asset contract reference is set
     * @param assetType The type of the asset
     * @param assetAddress The address of the asset
     */
    event SetAsset(uint256 indexed assetType, address indexed assetAddress);

    /**
     * @notice Emitted when the asset is removed
     * @param assetType The type of the asset
     */
    event RemoveAsset(uint256 indexed assetType);

    /**
     * @notice Emitted when a chain ID and CCTP domain pair is added or updated
     * @param chainId The chain ID
     * @param domain The CCTP domain
     */
    event SetChainDomain(uint256 indexed chainId, uint32 indexed domain);

    /**
     * @notice Emitted when a chain ID and CCTP domain pair is removed
     * @param chainId The chain ID
     * @param domain The CCTP domain
     */
    event RemoveChainDomain(uint256 indexed chainId, uint32 indexed domain);

    /**
     * @notice Emitted when the address of the processing fee collector is set
     * @param processingFeeCollector The address of the processing fee collector
     */
    event SetProcessingFeeCollector(address indexed processingFeeCollector);

    /**
     * @notice Emitted when the address of the target executor is set
     * @param account The address of the target executor
     * @param flag Target executor state flag
     */
    event SetTargetExecutor(address indexed account, bool indexed flag);

    /**
     * @notice Emitted on "sendMessage" call
     * @param extraData The extra data
     */
    event SendMessageExtraData(bytes extraData);

    /**
     * @notice Emitted when the specified asset address is duplicate
     */
    error DuplicateAssetAddressError(address account);

    /**
     * @notice Emitted when the domain for the specified chain is not set
     */
    error DomainNotSetError();

    /**
     * @notice Emitted when the provided call value is not sufficient for the message processing
     */
    error ProcessingFeeError();

    /**
     * @notice Emitted when the target chain gateway client contract is not set
     */
    error TargetClientNotSetError();

    /**
     * @notice Emitted when the message receiving fails
     */
    error ReceiveMessageError();

    /**
     * @notice Emitted when the message source address does not match the registered peer gateway on the target chain
     * @param sourceChainId The ID of the message source chain
     * @param fromAddress The address of the message source
     */
    error TargetFromAddressError(uint256 sourceChainId, address fromAddress);

    /**
     * @notice Emitted when the mint recipient is not the current contract
     * @param mintRecipient The address of the mint recipient
     */
    error TargetMintRecipientError(address mintRecipient);

    /**
     * @notice Emitted when the caller is not allowed to perform the action on the target chain
     */
    error TargetCallerError();

    /**
     * @notice Emitted when the gas reserve on the target chain does not allow further action processing
     */
    error TargetGasReserveError();

    /**
     * @notice Initializes the contract
     * @param _cctpTokenMessengerV2 The token messenger contract reference
     * @param _cctpMessageTransmitterV2 The message transmitter contract reference
     * @param _assetData The asset data
     * @param _chainDomains The list of registered chain domains
     * @param _targetGasReserve The initial gas reserve value for target chain action processing
     * @param _processingFeeCollector The initial address of the processing fee collector
     * @param _initialTargetExecutor The address of the target executor
     * @param _owner The address of the initial owner of the contract
     * @param _managers The addresses of initial managers of the contract
     * @param _addOwnerToManagers The flag to optionally add the owner to the list of managers
     */
    constructor(
        ITokenMessengerV2 _cctpTokenMessengerV2,
        IMessageTransmitterV2 _cctpMessageTransmitterV2,
        AssetDataItem[] memory _assetData,
        ChainDomain[] memory _chainDomains,
        uint256 _targetGasReserve,
        address _processingFeeCollector,
        address _initialTargetExecutor,
        address _owner,
        address[] memory _managers,
        bool _addOwnerToManagers
    ) {
        _setEndpoints(_cctpTokenMessengerV2, _cctpMessageTransmitterV2, true);

        for (uint256 index; index < _assetData.length; index++) {
            AssetDataItem memory assetDataItem = _assetData[index];

            _setAsset(assetDataItem.assetType, assetDataItem.assetAddress);
        }

        for (uint256 index; index < _chainDomains.length; index++) {
            ChainDomain memory chainDomain = _chainDomains[index];

            _setChainDomain(chainDomain.chainId, chainDomain.domain);
        }

        _setTargetGasReserve(_targetGasReserve);

        _setProcessingFeeCollector(_processingFeeCollector);

        if (_initialTargetExecutor != address(0)) {
            _setTargetExecutor(_initialTargetExecutor, true);
        }

        _initRoles(_owner, _managers, _addOwnerToManagers);
    }

    /**
     * @notice The standard "receive" function
     */
    receive() external payable {}

    /**
     * @notice Sets the cross-chain endpoint contract references
     * @param _cctpTokenMessengerV2 The token messenger contract reference
     * @param _cctpMessageTransmitterV2 The message transmitter contract reference
     */
    function setEndpoints(
        ITokenMessengerV2 _cctpTokenMessengerV2,
        IMessageTransmitterV2 _cctpMessageTransmitterV2
    ) external onlyManager {
        _setEndpoints(_cctpTokenMessengerV2, _cctpMessageTransmitterV2, false);
    }

    /**
     * @notice Adds or updates a registered asset
     * @param _assetType The type of the registered asset
     * @param _assetAddress The address of the registered asset
     */
    function setAsset(uint256 _assetType, address _assetAddress) external onlyManager {
        _setAsset(_assetType, _assetAddress);
    }

    /**
     * @notice Removes a registered asset
     * @param _assetType The type of the registered asset
     */
    function removeAsset(uint256 _assetType) external onlyManager {
        address assetAddress = assetMap[_assetType];

        DataStructures.combinedMapRemove(assetMap, assetTypeList, assetTypeIndexMap, _assetType);

        delete isAssetAddress[assetAddress];

        emit RemoveAsset(_assetType);
    }

    /**
     * @notice Adds or updates registered chain domains (CCTP-specific)
     * @param _chainDomains The list of registered chain domains
     */
    function setChainDomains(ChainDomain[] calldata _chainDomains) external onlyManager {
        for (uint256 index; index < _chainDomains.length; index++) {
            ChainDomain calldata chainDomain = _chainDomains[index];

            _setChainDomain(chainDomain.chainId, chainDomain.domain);
        }
    }

    /**
     * @notice Removes registered chain domains (CCTP-specific)
     * @param _chainIds The list of EVM chain IDs
     */
    function removeChainDomains(uint256[] calldata _chainIds) external onlyManager {
        for (uint256 index; index < _chainIds.length; index++) {
            uint256 chainId = _chainIds[index];

            _removeChainDomain(chainId);
        }
    }

    /**
     * @notice Sets the address of the processing fee collector
     * @param _processingFeeCollector The address of the processing fee collector
     */
    function setProcessingFeeCollector(address _processingFeeCollector) external onlyManager {
        _setProcessingFeeCollector(_processingFeeCollector);
    }

    /**
     * @notice Sets the address of the target executor
     * @param _account The address of the target executor
     * @param _flag Target executor state flag
     */
    function setTargetExecutor(address _account, bool _flag) external onlyManager {
        _setTargetExecutor(_account, _flag);
    }

    /**
     * @notice Send a cross-chain message
     * @dev The settings parameter contains an ABI-encoded uint256 value of the target chain gas
     * @param _targetChainId The message target chain ID
     * @param _appMessage The app message content
     * @param _settings The gateway-specific settings
     * @param _assetAmountData The asset amount data
     */
    function sendMessage(
        uint256 _targetChainId,
        bytes calldata _appMessage,
        bytes calldata _settings,
        AssetAmountData calldata _assetAmountData
    ) external payable onlyClient whenNotPaused {
        (uint32 targetDomain, bytes32 peerAddressBytes32) = _checkChain(_targetChainId);

        (
            uint256 maxFee,
            uint32 minFinalityThreshold,
            uint256 processingFee,
            bytes memory extraData
        ) = _decodeSettings(_settings);

        // - - - Processing fee transfer - - -

        if (msg.value < processingFee) {
            revert ProcessingFeeError();
        }

        if (processingFee > 0 && processingFeeCollector != address(0)) {
            TransferHelper.safeTransferNative(processingFeeCollector, processingFee);
        }

        address token = assetMap[_assetAmountData.assetType];

        TransferHelper.safeTransferFrom(token, msg.sender, address(this), _assetAmountData.amount);

        TransferHelper.safeApprove(token, address(cctpTokenMessengerV2), _assetAmountData.amount);

        bytes calldata appMessage = _appMessage; // stack too deep

        ITokenMessengerV2(cctpTokenMessengerV2).depositForBurnWithHook(
            _assetAmountData.amount,
            targetDomain,
            peerAddressBytes32,
            token,
            peerAddressBytes32,
            maxFee,
            minFinalityThreshold,
            appMessage
        );

        TransferHelper.safeApprove(token, address(cctpTokenMessengerV2), 0);

        emit SendMessageExtraData(extraData);
    }

    /**
     * @notice Executes the target actions
     * @param _message The CCTP V2 message
     * @param _attestation The CCTP V2 attestation
     */
    function executeTarget(
        bytes calldata _message,
        bytes calldata _attestation
    ) external whenNotPaused nonReentrant {
        if (address(client) == address(0)) {
            revert TargetClientNotSetError();
        }

        (
            uint32 sourceDomain,
            address mintRecipient,
            address messageSender,
            bytes calldata hookData
        ) = CCTPV2MessageHelper.extractMessageFields(_message);

        IActionDataStructures.TargetMessage memory targetMessage = abi.decode(
            hookData,
            (IActionDataStructures.TargetMessage)
        );

        bool targetCallerCondition = isTargetExecutor[msg.sender] ||
            msg.sender == targetMessage.sourceSender ||
            msg.sender == targetMessage.targetRecipient;

        if (!targetCallerCondition) {
            revert TargetCallerError();
        }

        uint256 sourceStandardChainId = domainToChainId[sourceDomain];

        // stack too deep
        {
            bool condition = sourceStandardChainId != 0 &&
                messageSender != address(0) &&
                messageSender == peerMap[sourceStandardChainId];

            if (!condition) {
                revert TargetFromAddressError(sourceStandardChainId, messageSender);
            }
        }

        if (mintRecipient != address(this)) {
            revert TargetMintRecipientError(mintRecipient);
        }

        bytes calldata message = _message; // stack too deep
        bytes calldata attestation = _attestation; // stack too deep
        bytes calldata appMessage = hookData; // stack too deep

        address assetAddress = assetMap[targetMessage.assetType];
        uint256 assetBalanceBefore = tokenBalance(assetAddress);

        bool receiveMessageSuccess;

        try cctpMessageTransmitterV2.receiveMessage(message, attestation) returns (bool success) {
            receiveMessageSuccess = success;
        } catch {}

        if (!receiveMessageSuccess) {
            revert ReceiveMessageError();
        }

        uint256 assetAmount = tokenBalance(assetAddress) - assetBalanceBefore;

        TransferHelper.safeApprove(assetAddress, address(client), assetAmount);

        (bool hasGasReserve, uint256 gasAllowed) = GasReserveHelper.checkGasReserve(
            targetGasReserve
        );

        if (!hasGasReserve) {
            revert TargetGasReserveError();
        }

        client.handleExecutionPayload{ gas: gasAllowed }(
            sourceStandardChainId,
            appMessage,
            assetAddress,
            assetAmount
        );

        TransferHelper.safeApprove(assetAddress, address(client), 0);
    }

    /**
     * @notice Cross-chain message fee estimation (native token fee only)
     * @return nativeFee Message fee (native token)
     */
    function messageFee(
        uint256 /*_targetChainId*/,
        bytes calldata /*_appMessage*/,
        bytes calldata /*_settings*/,
        AssetAmountData calldata /*_assetAmountData*/
    ) external pure returns (uint256 nativeFee) {
        return 0;
    }

    /**
     * @notice Target chain amount estimation (local decimals)
     * @param _assetAmountData The asset amount data
     * @return amount Target chain amount
     */
    function targetAmountLD(
        uint256 /*_targetChainId*/,
        AssetAmountData calldata _assetAmountData
    ) external pure returns (uint256 amount) {
        return _assetAmountData.amount; // the "fast burn" fee is available via API
    }

    /**
     * @notice Asset transfer limits
     * @param _assetType The asset type
     * @return limit Asset transfer limit in SD (shared decimals)
     * @return sharedDecimals Shared decimals
     */
    function assetLimit(
        uint256 /*_targetChainId*/,
        uint256 _assetType
    ) external view returns (uint256 limit, uint8 sharedDecimals) {
        address tokenAddress = assetMap[_assetType];
        ITokenController tokenController = ITokenController(cctpTokenMessengerV2.localMinter());

        limit = tokenController.burnLimitsPerMessage(tokenAddress);
        sharedDecimals = ITokenDecimals(tokenAddress).decimals();
    }

    /**
     * @notice Asset address by type
     * @param _assetType The asset type
     * @return The asset address
     */
    function assetByType(uint256 _assetType) external view returns (address) {
        return assetMap[_assetType];
    }

    /**
     * @notice Getter of registered asset type count
     * @return Registered asset type count
     */
    function assetTypeCount() external view returns (uint256) {
        return assetTypeList.length;
    }

    /**
     * @notice Getter of the complete list of registered asset types
     * @return The complete list of registered asset types
     */
    function fullAssetTypeList() external view returns (uint256[] memory) {
        return assetTypeList;
    }

    /**
     * @notice Getter of the complete asset data
     * @return assetData The complete asset data: asset types and addresses
     */
    function fullAssetData() external view returns (AssetDataItem[] memory assetData) {
        uint256 assetTypeListLength = assetTypeList.length;

        assetData = new AssetDataItem[](assetTypeListLength);

        uint256 assetType;

        for (uint256 index; index < assetTypeListLength; index++) {
            assetType = assetTypeList[index];

            assetData[index] = AssetDataItem({
                assetType: assetType,
                assetAddress: assetMap[assetType]
            });
        }
    }

    function _setEndpoints(
        ITokenMessengerV2 _cctpTokenMessengerV2,
        IMessageTransmitterV2 _cctpMessageTransmitterV2,
        bool _zeroAddressAllowed
    ) private {
        if (_zeroAddressAllowed) {
            AddressHelper.requireContractOrZeroAddress(address(_cctpTokenMessengerV2));
            AddressHelper.requireContractOrZeroAddress(address(_cctpMessageTransmitterV2));
        } else {
            AddressHelper.requireContract(address(_cctpTokenMessengerV2));
            AddressHelper.requireContract(address(_cctpMessageTransmitterV2));
        }

        cctpTokenMessengerV2 = _cctpTokenMessengerV2;
        cctpMessageTransmitterV2 = _cctpMessageTransmitterV2;

        emit SetEndpoints(_cctpTokenMessengerV2, _cctpMessageTransmitterV2);
    }

    function _setAsset(uint256 _assetType, address _assetAddress) private {
        address previousAssetAddress = assetMap[_assetType];

        if (_assetAddress != previousAssetAddress) {
            if (isAssetAddress[_assetAddress]) {
                revert DuplicateAssetAddressError(_assetAddress); // The address is set for another asset type
            }

            AddressHelper.requireContract(_assetAddress);

            DataStructures.combinedMapSet(
                assetMap,
                assetTypeList,
                assetTypeIndexMap,
                _assetType,
                _assetAddress,
                Constants.LIST_SIZE_LIMIT_DEFAULT
            );

            if (previousAssetAddress != address(0)) {
                delete isAssetAddress[previousAssetAddress];
            }

            isAssetAddress[_assetAddress] = true;
        }

        emit SetAsset(_assetType, _assetAddress);
    }

    function _setChainDomain(uint256 _chainId, uint32 _domain) private {
        DataStructures.OptionalValue storage previousDomainEntry = chainIdToDomain[_chainId];

        if (previousDomainEntry.isSet) {
            delete domainToChainId[uint32(previousDomainEntry.value)];
        }

        chainIdToDomain[_chainId] = DataStructures.OptionalValue({ isSet: true, value: _domain });
        domainToChainId[_domain] = _chainId;

        emit SetChainDomain(_chainId, _domain);
    }

    function _removeChainDomain(uint256 _chainId) private {
        DataStructures.OptionalValue storage domainEntry = chainIdToDomain[_chainId];

        uint32 domain;

        if (domainEntry.isSet) {
            domain = uint32(domainEntry.value);

            delete domainToChainId[uint32(domainEntry.value)];
        }

        delete chainIdToDomain[_chainId];

        emit RemoveChainDomain(_chainId, domain);
    }

    function _setProcessingFeeCollector(address _processingFeeCollector) private {
        processingFeeCollector = _processingFeeCollector;

        emit SetProcessingFeeCollector(_processingFeeCollector);
    }

    function _setTargetExecutor(address _account, bool _flag) private {
        isTargetExecutor[_account] = _flag;

        emit SetTargetExecutor(_account, _flag);
    }

    function _checkChain(
        uint256 _chainId
    ) private view returns (uint32 domain, bytes32 peerAddressBytes32) {
        DataStructures.OptionalValue storage domainEntry = chainIdToDomain[_chainId];

        if (!domainEntry.isSet) {
            revert DomainNotSetError();
        }

        domain = uint32(domainEntry.value);

        address peerAddress = peerMap[_chainId];

        if (peerAddress == address(0)) {
            revert PeerNotSetError();
        }

        peerAddressBytes32 = _addressToBytes32(peerAddress);
    }

    function _decodeSettings(
        bytes calldata _settings
    )
        private
        pure
        returns (
            uint256 maxFee,
            uint32 minFinalityThreshold,
            uint256 processingFee,
            bytes memory extraData
        )
    {
        return abi.decode(_settings, (uint256, uint32, uint256, bytes));
    }

    function _addressToBytes32(address _address) private pure returns (bytes32) {
        return bytes32(uint256(uint160(_address)));
    }

    function _bytes32ToAddress(bytes32 _buffer) private pure returns (address) {
        return address(uint160(uint256(_buffer)));
    }
}

interface ITokenMessengerV2 {
    function depositForBurnWithHook(
        uint256 _amount,
        uint32 _destinationDomain,
        bytes32 _mintRecipient,
        address _burnToken,
        bytes32 _destinationCaller,
        uint256 _maxFee,
        uint32 _minFinalityThreshold,
        bytes calldata _hookData
    ) external;

    function localMinter() external view returns (address);
}

interface IMessageTransmitterV2 {
    function receiveMessage(
        bytes calldata _message,
        bytes calldata _attestation
    ) external returns (bool success);
}

interface ITokenController {
    function burnLimitsPerMessage(address _burnToken) external view returns (uint256);
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/security/Pausable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

@openzeppelin/contracts/security/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

contracts/BalanceManagement.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

import { ITokenBalance } from './interfaces/ITokenBalance.sol';
import { ManagerRole } from './roles/ManagerRole.sol';
import './helpers/TransferHelper.sol' as TransferHelper;
import './Constants.sol' as Constants;

/**
 * @title BalanceManagement
 * @notice Base contract for the withdrawal of tokens, except for reserved ones
 */
abstract contract BalanceManagement is ManagerRole {
    /**
     * @notice Emitted when the specified token is reserved
     */
    error ReservedTokenError();

    /**
     * @notice Performs the withdrawal of tokens, except for reserved ones
     * @dev Use the "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" address for the native token
     * @param _tokenAddress The address of the token
     * @param _tokenAmount The amount of the token
     */
    function cleanup(address _tokenAddress, uint256 _tokenAmount) external onlyManager {
        if (isReservedToken(_tokenAddress)) {
            revert ReservedTokenError();
        }

        if (_tokenAddress == Constants.NATIVE_TOKEN_ADDRESS) {
            TransferHelper.safeTransferNative(msg.sender, _tokenAmount);
        } else {
            TransferHelper.safeTransfer(_tokenAddress, msg.sender, _tokenAmount);
        }
    }

    /**
     * @notice Getter of the token balance of the current contract
     * @dev Use the "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" address for the native token
     * @param _tokenAddress The address of the token
     * @return The token balance of the current contract
     */
    function tokenBalance(address _tokenAddress) public view returns (uint256) {
        if (_tokenAddress == Constants.NATIVE_TOKEN_ADDRESS) {
            return address(this).balance;
        } else {
            return ITokenBalance(_tokenAddress).balanceOf(address(this));
        }
    }

    /**
     * @notice Getter of the reserved token flag
     * @dev Override to add reserved token addresses
     * @param _tokenAddress The address of the token
     * @return The reserved token flag
     */
    function isReservedToken(address _tokenAddress) public view virtual returns (bool) {
        // The function returns false by default.
        // The explicit return statement is omitted to avoid the unused parameter warning.
        // See https://github.com/ethereum/solidity/issues/5295
    }
}

contracts/Constants.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

/**
 * @dev The default token decimals value
 */
uint256 constant DECIMALS_DEFAULT = 18;

/**
 * @dev The maximum uint256 value for swap amount limit settings
 */
uint256 constant INFINITY = type(uint256).max;

/**
 * @dev The default limit of account list size
 */
uint256 constant LIST_SIZE_LIMIT_DEFAULT = 100;

/**
 * @dev The limit of swap router list size
 */
uint256 constant LIST_SIZE_LIMIT_ROUTERS = 200;

/**
 * @dev The factor for percentage settings. Example: 100 is 0.1%
 */
uint256 constant MILLIPERCENT_FACTOR = 100_000;

/**
 * @dev The de facto standard address to denote the native token
 */
address constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

contracts/DataStructures.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

/**
 * @notice Optional value structure
 * @dev Is used in mappings to allow zero values
 * @param isSet Value presence flag
 * @param value Numeric value
 */
struct OptionalValue {
    bool isSet;
    uint256 value;
}

/**
 * @notice Key-to-value structure
 * @dev Is used as an array parameter item to perform multiple key-value settings
 * @param key Numeric key
 * @param value Numeric value
 */
struct KeyToValue {
    uint256 key;
    uint256 value;
}

/**
 * @notice Key-to-value structure for address values
 * @dev Is used as an array parameter item to perform multiple key-value settings with address values
 * @param key Numeric key
 * @param value Address value
 */
struct KeyToAddressValue {
    uint256 key;
    address value;
}

/**
 * @notice Address-to-flag structure
 * @dev Is used as an array parameter item to perform multiple settings
 * @param account Account address
 * @param flag Flag value
 */
struct AccountToFlag {
    address account;
    bool flag;
}

/**
 * @notice Emitted when a list exceeds the size limit
 */
error ListSizeLimitError();

/**
 * @notice Sets or updates a value in a combined map (a mapping with a key list and key index mapping)
 * @param _map The mapping reference
 * @param _keyList The key list reference
 * @param _keyIndexMap The key list index mapping reference
 * @param _key The numeric key
 * @param _value The address value
 * @param _sizeLimit The map and list size limit
 * @return isNewKey True if the key was just added, otherwise false
 */
function combinedMapSet(
    mapping(uint256 => address) storage _map,
    uint256[] storage _keyList,
    mapping(uint256 => OptionalValue) storage _keyIndexMap,
    uint256 _key,
    address _value,
    uint256 _sizeLimit
) returns (bool isNewKey) {
    isNewKey = !_keyIndexMap[_key].isSet;

    if (isNewKey) {
        uniqueListAdd(_keyList, _keyIndexMap, _key, _sizeLimit);
    }

    _map[_key] = _value;
}

/**
 * @notice Removes a value from a combined map (a mapping with a key list and key index mapping)
 * @param _map The mapping reference
 * @param _keyList The key list reference
 * @param _keyIndexMap The key list index mapping reference
 * @param _key The numeric key
 * @return isChanged True if the combined map was changed, otherwise false
 */
function combinedMapRemove(
    mapping(uint256 => address) storage _map,
    uint256[] storage _keyList,
    mapping(uint256 => OptionalValue) storage _keyIndexMap,
    uint256 _key
) returns (bool isChanged) {
    isChanged = _keyIndexMap[_key].isSet;

    if (isChanged) {
        delete _map[_key];
        uniqueListRemove(_keyList, _keyIndexMap, _key);
    }
}

/**
 * @notice Sets or updates a value in a combined double map (two mappings with a key list and key index mapping)
 * @param _map1 The first mapping reference
 * @param _map2 The second mapping reference
 * @param _keyList The key list reference
 * @param _keyIndexMap The key list index mapping reference
 * @param _key The numeric key
 * @param _value1 The first address value
 * @param _value2 The second address value
 * @param _sizeLimit The map and list size limit
 * @return isNewKey True if the key was just added, otherwise false
 */
function combinedDoubleMapSet(
    mapping(uint256 => address) storage _map1,
    mapping(uint256 => address) storage _map2,
    uint256[] storage _keyList,
    mapping(uint256 => OptionalValue) storage _keyIndexMap,
    uint256 _key,
    address _value1,
    address _value2,
    uint256 _sizeLimit
) returns (bool isNewKey) {
    isNewKey = !_keyIndexMap[_key].isSet;

    if (isNewKey) {
        uniqueListAdd(_keyList, _keyIndexMap, _key, _sizeLimit);
    }

    _map1[_key] = _value1;
    _map2[_key] = _value2;
}

/**
 * @notice Removes a value from a combined double map (two mappings with a key list and key index mapping)
 * @param _map1 The first mapping reference
 * @param _map2 The second mapping reference
 * @param _keyList The key list reference
 * @param _keyIndexMap The key list index mapping reference
 * @param _key The numeric key
 * @return isChanged True if the combined map was changed, otherwise false
 */
function combinedDoubleMapRemove(
    mapping(uint256 => address) storage _map1,
    mapping(uint256 => address) storage _map2,
    uint256[] storage _keyList,
    mapping(uint256 => OptionalValue) storage _keyIndexMap,
    uint256 _key
) returns (bool isChanged) {
    isChanged = _keyIndexMap[_key].isSet;

    if (isChanged) {
        delete _map1[_key];
        delete _map2[_key];
        uniqueListRemove(_keyList, _keyIndexMap, _key);
    }
}

/**
 * @notice Adds a value to a unique value list (a list with value index mapping)
 * @param _list The list reference
 * @param _indexMap The value index mapping reference
 * @param _value The numeric value
 * @param _sizeLimit The list size limit
 * @return isChanged True if the list was changed, otherwise false
 */
function uniqueListAdd(
    uint256[] storage _list,
    mapping(uint256 => OptionalValue) storage _indexMap,
    uint256 _value,
    uint256 _sizeLimit
) returns (bool isChanged) {
    isChanged = !_indexMap[_value].isSet;

    if (isChanged) {
        if (_list.length >= _sizeLimit) {
            revert ListSizeLimitError();
        }

        _indexMap[_value] = OptionalValue(true, _list.length);
        _list.push(_value);
    }
}

/**
 * @notice Removes a value from a unique value list (a list with value index mapping)
 * @param _list The list reference
 * @param _indexMap The value index mapping reference
 * @param _value The numeric value
 * @return isChanged True if the list was changed, otherwise false
 */
function uniqueListRemove(
    uint256[] storage _list,
    mapping(uint256 => OptionalValue) storage _indexMap,
    uint256 _value
) returns (bool isChanged) {
    OptionalValue storage indexItem = _indexMap[_value];

    isChanged = indexItem.isSet;

    if (isChanged) {
        uint256 itemIndex = indexItem.value;
        uint256 lastIndex = _list.length - 1;

        if (itemIndex != lastIndex) {
            uint256 lastValue = _list[lastIndex];
            _list[itemIndex] = lastValue;
            _indexMap[lastValue].value = itemIndex;
        }

        _list.pop();
        delete _indexMap[_value];
    }
}

/**
 * @notice Adds a value to a unique address value list (a list with value index mapping)
 * @param _list The list reference
 * @param _indexMap The value index mapping reference
 * @param _value The address value
 * @param _sizeLimit The list size limit
 * @return isChanged True if the list was changed, otherwise false
 */
function uniqueAddressListAdd(
    address[] storage _list,
    mapping(address => OptionalValue) storage _indexMap,
    address _value,
    uint256 _sizeLimit
) returns (bool isChanged) {
    isChanged = !_indexMap[_value].isSet;

    if (isChanged) {
        if (_list.length >= _sizeLimit) {
            revert ListSizeLimitError();
        }

        _indexMap[_value] = OptionalValue(true, _list.length);
        _list.push(_value);
    }
}

/**
 * @notice Removes a value from a unique address value list (a list with value index mapping)
 * @param _list The list reference
 * @param _indexMap The value index mapping reference
 * @param _value The address value
 * @return isChanged True if the list was changed, otherwise false
 */
function uniqueAddressListRemove(
    address[] storage _list,
    mapping(address => OptionalValue) storage _indexMap,
    address _value
) returns (bool isChanged) {
    OptionalValue storage indexItem = _indexMap[_value];

    isChanged = indexItem.isSet;

    if (isChanged) {
        uint256 itemIndex = indexItem.value;
        uint256 lastIndex = _list.length - 1;

        if (itemIndex != lastIndex) {
            address lastValue = _list[lastIndex];
            _list[itemIndex] = lastValue;
            _indexMap[lastValue].value = itemIndex;
        }

        _list.pop();
        delete _indexMap[_value];
    }
}

/**
 * @notice Adds or removes a value to/from a unique address value list (a list with value index mapping)
 * @dev The list size limit is checked on items adding only
 * @param _list The list reference
 * @param _indexMap The value index mapping reference
 * @param _value The address value
 * @param _flag The value inclusion flag
 * @param _sizeLimit The list size limit
 * @return isChanged True if the list was changed, otherwise false
 */
function uniqueAddressListUpdate(
    address[] storage _list,
    mapping(address => OptionalValue) storage _indexMap,
    address _value,
    bool _flag,
    uint256 _sizeLimit
) returns (bool isChanged) {
    return
        _flag
            ? uniqueAddressListAdd(_list, _indexMap, _value, _sizeLimit)
            : uniqueAddressListRemove(_list, _indexMap, _value);
}

contracts/Errors.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

/**
 * @notice Emitted when an attempt to burn a token fails
 */
error TokenBurnError();

/**
 * @notice Emitted when an attempt to mint a token fails
 */
error TokenMintError();

/**
 * @notice Emitted when a zero address is specified where it is not allowed
 */
error ZeroAddressError();

contracts/Pausable.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

import { Pausable as PausableBase } from '@openzeppelin/contracts/security/Pausable.sol';
import { ManagerRole } from './roles/ManagerRole.sol';

/**
 * @title Pausable
 * @notice Base contract that implements the emergency pause mechanism
 */
abstract contract Pausable is PausableBase, ManagerRole {
    /**
     * @notice Enter pause state
     */
    function pause() external onlyManager whenNotPaused {
        _pause();
    }

    /**
     * @notice Exit pause state
     */
    function unpause() external onlyManager whenPaused {
        _unpause();
    }
}

contracts/SystemVersionId.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

/**
 * @title SystemVersionId
 * @notice Base contract providing the system version identifier
 */
abstract contract SystemVersionId {
    /**
     * @dev The system version identifier
     */
    uint256 public constant SYSTEM_VERSION_ID = uint256(keccak256('Initial-2025-01-22'));
}

contracts/crosschain/GatewayBase.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

import { ReentrancyGuard } from '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import { IGateway } from './interfaces/IGateway.sol';
import { IGatewayClient } from './interfaces/IGatewayClient.sol';
import { BalanceManagement } from '../BalanceManagement.sol';
import { Pausable } from '../Pausable.sol';
import { TargetGasReserve } from './TargetGasReserve.sol';
import { ZeroAddressError } from '../Errors.sol';
import '../helpers/AddressHelper.sol' as AddressHelper;
import '../Constants.sol' as Constants;
import '../DataStructures.sol' as DataStructures;

/**
 * @title GatewayBase
 * @notice Base contract that implements the cross-chain gateway logic
 */
abstract contract GatewayBase is
    Pausable,
    ReentrancyGuard,
    TargetGasReserve,
    BalanceManagement,
    IGateway
{
    /**
     * @dev Gateway client contract reference
     */
    IGatewayClient public client;

    /**
     * @dev Registered peer gateway addresses by the chain ID
     */
    mapping(uint256 /*peerChainId*/ => address /*peerAddress*/) public peerMap;

    /**
     * @dev Registered peer gateway chain IDs
     */
    uint256[] public peerChainIdList;

    /**
     * @dev Registered peer gateway chain ID indices
     */
    mapping(uint256 /*peerChainId*/ => DataStructures.OptionalValue /*peerChainIdIndex*/)
        public peerChainIdIndexMap;

    /**
     * @notice Emitted when the gateway client contract reference is set
     * @param clientAddress The gateway client contract address
     */
    event SetClient(address indexed clientAddress);

    /**
     * @notice Emitted when a registered peer gateway contract address is added or updated
     * @param chainId The chain ID of the registered peer gateway
     * @param peerAddress The address of the registered peer gateway contract
     */
    event SetPeer(uint256 indexed chainId, address indexed peerAddress);

    /**
     * @notice Emitted when a registered peer gateway contract address is removed
     * @param chainId The chain ID of the registered peer gateway
     */
    event RemovePeer(uint256 indexed chainId);

    /**
     * @notice Emitted when the target chain gateway is paused
     */
    event TargetPausedFailure();

    /**
     * @notice Emitted when the target chain gateway client contract is not set
     */
    event TargetClientNotSetFailure();

    /**
     * @notice Emitted when the message source address does not match the registered peer gateway on the target chain
     * @param sourceChainId The ID of the message source chain
     * @param fromAddress The address of the message source
     */
    event TargetFromAddressFailure(uint256 indexed sourceChainId, address indexed fromAddress);

    /**
     * @notice Emitted when the gas reserve on the target chain does not allow further action processing
     * @param sourceChainId The ID of the message source chain
     */
    event TargetGasReserveFailure(uint256 indexed sourceChainId);

    /**
     * @notice Emitted when the gateway client execution on the target chain fails
     */
    event TargetExecutionFailure();

    /**
     * @notice Emitted when the caller is not the gateway client contract
     */
    error OnlyClientError();

    /**
     * @notice Emitted when the peer config address for the current chain does not match the current contract
     */
    error PeerAddressMismatchError();

    /**
     * @notice Emitted when the peer gateway address for the specified chain is not set
     */
    error PeerNotSetError();

    /**
     * @notice Emitted when the chain ID is not set
     */
    error ZeroChainIdError();

    /**
     * @dev Modifier to check if the caller is the gateway client contract
     */
    modifier onlyClient() {
        if (msg.sender != address(client)) {
            revert OnlyClientError();
        }

        _;
    }

    /**
     * @notice Sets the gateway client contract reference
     * @param _clientAddress The gateway client contract address
     */
    function setClient(address payable _clientAddress) external virtual onlyManager {
        AddressHelper.requireContract(_clientAddress);

        client = IGatewayClient(_clientAddress);

        emit SetClient(_clientAddress);
    }

    /**
     * @notice Adds or updates registered peer gateways
     * @param _peers Chain IDs and addresses of peer gateways
     */
    function setPeers(
        DataStructures.KeyToAddressValue[] calldata _peers
    ) external virtual onlyManager {
        for (uint256 index; index < _peers.length; index++) {
            DataStructures.KeyToAddressValue calldata item = _peers[index];

            uint256 chainId = item.key;
            address peerAddress = item.value;

            // Allow the same configuration on multiple chains
            if (chainId == block.chainid) {
                if (peerAddress != address(this)) {
                    revert PeerAddressMismatchError();
                }
            } else {
                _setPeer(chainId, peerAddress);
            }
        }
    }

    /**
     * @notice Removes registered peer gateways
     * @param _chainIds Peer gateway chain IDs
     */
    function removePeers(uint256[] calldata _chainIds) external virtual onlyManager {
        for (uint256 index; index < _chainIds.length; index++) {
            uint256 chainId = _chainIds[index];

            // Allow the same configuration on multiple chains
            if (chainId != block.chainid) {
                _removePeer(chainId);
            }
        }
    }

    /**
     * @notice Getter of the peer gateway count
     * @return The peer gateway count
     */
    function peerCount() external view virtual returns (uint256) {
        return peerChainIdList.length;
    }

    /**
     * @notice Getter of the complete list of the peer gateway chain IDs
     * @return The complete list of the peer gateway chain IDs
     */
    function fullPeerChainIdList() external view virtual returns (uint256[] memory) {
        return peerChainIdList;
    }

    function _setPeer(uint256 _chainId, address _peerAddress) internal virtual {
        if (_chainId == 0) {
            revert ZeroChainIdError();
        }

        if (_peerAddress == address(0)) {
            revert ZeroAddressError();
        }

        DataStructures.combinedMapSet(
            peerMap,
            peerChainIdList,
            peerChainIdIndexMap,
            _chainId,
            _peerAddress,
            Constants.LIST_SIZE_LIMIT_DEFAULT
        );

        emit SetPeer(_chainId, _peerAddress);
    }

    function _removePeer(uint256 _chainId) internal virtual {
        if (_chainId == 0) {
            revert ZeroChainIdError();
        }

        DataStructures.combinedMapRemove(peerMap, peerChainIdList, peerChainIdIndexMap, _chainId);

        emit RemovePeer(_chainId);
    }

    function _checkPeerAddress(uint256 _chainId) internal virtual returns (address) {
        address peerAddress = peerMap[_chainId];

        if (peerAddress == address(0)) {
            revert PeerNotSetError();
        }

        return peerAddress;
    }
}

contracts/crosschain/TargetGasReserve.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

import { ManagerRole } from '../roles/ManagerRole.sol';

/**
 * @title TargetGasReserve
 * @notice Base contract that implements the gas reserve logic for the target chain actions
 */
abstract contract TargetGasReserve is ManagerRole {
    /**
     * @dev The target chain gas reserve value
     */
    uint256 public targetGasReserve;

    /**
     * @notice Emitted when the target chain gas reserve value is set
     * @param gasReserve The target chain gas reserve value
     */
    event SetTargetGasReserve(uint256 gasReserve);

    /**
     * @notice Sets the target chain gas reserve value
     * @param _gasReserve The target chain gas reserve value
     */
    function setTargetGasReserve(uint256 _gasReserve) external onlyManager {
        _setTargetGasReserve(_gasReserve);
    }

    function _setTargetGasReserve(uint256 _gasReserve) internal virtual {
        targetGasReserve = _gasReserve;

        emit SetTargetGasReserve(_gasReserve);
    }
}

contracts/crosschain/circle-cctp-v2/helpers/CCTPV2MessageHelper.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

/**
 * @notice Function to extract CCTP V2 message fields
 * @param _message The CCTP V2 message
 * @return sourceDomain Source domain
 * @return mintRecipient Mint recipient address
 * @return messageSender Message sender address
 * @return hookData Message hook data
 */
function extractMessageFields(
    bytes calldata _message
)
    pure
    returns (
        uint32 sourceDomain,
        address mintRecipient,
        address messageSender,
        bytes calldata hookData
    )
{
    sourceDomain = uint32(bytes4(_message[4:8]));
    mintRecipient = address(bytes20(_message[196:216]));
    messageSender = address(bytes20(_message[260:280]));
    hookData = _message[376:];
}

contracts/crosschain/interfaces/IGateway.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

import { IAssetDataStructures } from '../../interfaces/IAssetDataStructures.sol';

/**
 * @title IGateway
 * @notice Cross-chain gateway interface
 */
interface IGateway is IAssetDataStructures {
    /**
     * @notice Send a cross-chain message
     * @param _targetChainId The message target chain ID
     * @param _appMessage The app message content
     * @param _settings The gateway-specific settings
     * @param _assetAmountData The asset amount data
     */
    function sendMessage(
        uint256 _targetChainId,
        bytes calldata _appMessage,
        bytes calldata _settings,
        AssetAmountData calldata _assetAmountData
    ) external payable;

    /**
     * @notice Cross-chain message fee estimation (native token fee only)
     * @param _targetChainId The ID of the target chain
     * @param _appMessage The app message content
     * @param _settings The gateway-specific settings
     * @param _assetAmountData The asset amount data
     * @return nativeFee Message fee (native token)
     */
    function messageFee(
        uint256 _targetChainId,
        bytes calldata _appMessage,
        bytes calldata _settings,
        AssetAmountData calldata _assetAmountData
    ) external view returns (uint256 nativeFee);

    /**
     * @notice Target chain amount estimation (local decimals)
     * @param _targetChainId The ID of the target chain
     * @param _assetAmountData The asset amount data
     * @return amount Target chain amount
     */
    function targetAmountLD(
        uint256 _targetChainId,
        AssetAmountData calldata _assetAmountData
    ) external view returns (uint256 amount);

    /**
     * @notice Asset transfer limits
     * @param _targetChainId The ID of the target chain
     * @param _assetType The asset type
     * @return limit Asset transfer limit in SD (shared decimals)
     * @return sharedDecimals Shared decimals
     */
    function assetLimit(
        uint256 _targetChainId,
        uint256 _assetType
    ) external view returns (uint256 limit, uint8 sharedDecimals);

    /**
     * @notice Asset address by type
     * @param _assetType The asset type
     * @return The asset address
     */
    function assetByType(uint256 _assetType) external view returns (address);
}

contracts/crosschain/interfaces/IGatewayClient.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

import { IAssetDataStructures } from '../../interfaces/IAssetDataStructures.sol';

/**
 * @title IGatewayClient
 * @notice Cross-chain gateway client interface
 */
interface IGatewayClient is IAssetDataStructures {
    /**
     * @notice Cross-chain message handler on the target chain
     * @dev The function is called by cross-chain gateways
     * @param _messageSourceChainId The ID of the message source chain
     * @param _payloadData The content of the cross-chain message
     * @param _assetTokenAddress The asset token address
     * @param _assetAmount The asset amount
     */
    function handleExecutionPayload(
        uint256 _messageSourceChainId,
        bytes calldata _payloadData,
        address _assetTokenAddress,
        uint256 _assetAmount
    ) external payable;

    /**
     * @notice The standard "receive" function
     */
    receive() external payable;
}

contracts/helpers/AddressHelper.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

/**
 * @notice Emitted when the account is not a contract
 * @param account The account address
 */
error NonContractAddressError(address account);

/**
 * @notice Function to check if the account is a contract
 * @return The account contract status flag
 */
function isContract(address _account) view returns (bool) {
    return _account.code.length > 0;
}

/**
 * @notice Function to require an account to be a contract
 */
function requireContract(address _account) view {
    if (!isContract(_account)) {
        revert NonContractAddressError(_account);
    }
}

/**
 * @notice Function to require an account to be a contract or a zero address
 */
function requireContractOrZeroAddress(address _account) view {
    if (_account != address(0)) {
        requireContract(_account);
    }
}

contracts/helpers/GasReserveHelper.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

/**
 * @notice Function to check if the available gas matches the specified gas reserve value
 * @param _gasReserve Gas reserve value
 * @return hasGasReserve Flag of gas reserve availability
 * @return gasAllowed The remaining gas quantity taking the reserve into account
 */
function checkGasReserve(
    uint256 _gasReserve
) view returns (bool hasGasReserve, uint256 gasAllowed) {
    uint256 gasLeft = gasleft();

    hasGasReserve = gasLeft >= _gasReserve;
    gasAllowed = hasGasReserve ? gasLeft - _gasReserve : 0;
}

contracts/helpers/TransferHelper.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

/**
 * @notice Emitted when an approval action fails
 */
error SafeApproveError();

/**
 * @notice Emitted when a transfer action fails
 */
error SafeTransferError();

/**
 * @notice Emitted when a transferFrom action fails
 */
error SafeTransferFromError();

/**
 * @notice Emitted when a transfer of the native token fails
 */
error SafeTransferNativeError();

/**
 * @notice Safely approve the token to the account
 * @param _token The token address
 * @param _to The token approval recipient address
 * @param _value The token approval amount
 */
function safeApprove(address _token, address _to, uint256 _value) {
    // 0x095ea7b3 is the selector for "approve(address,uint256)"
    (bool success, bytes memory data) = _token.call(
        abi.encodeWithSelector(0x095ea7b3, _to, _value)
    );

    bool condition = success && (data.length == 0 || abi.decode(data, (bool)));

    if (!condition) {
        revert SafeApproveError();
    }
}

/**
 * @notice Safely transfer the token to the account
 * @param _token The token address
 * @param _to The token transfer recipient address
 * @param _value The token transfer amount
 */
function safeTransfer(address _token, address _to, uint256 _value) {
    // 0xa9059cbb is the selector for "transfer(address,uint256)"
    (bool success, bytes memory data) = _token.call(
        abi.encodeWithSelector(0xa9059cbb, _to, _value)
    );

    bool condition = success && (data.length == 0 || abi.decode(data, (bool)));

    if (!condition) {
        revert SafeTransferError();
    }
}

/**
 * @notice Safely transfer the token between the accounts
 * @param _token The token address
 * @param _from The token transfer source address
 * @param _to The token transfer recipient address
 * @param _value The token transfer amount
 */
function safeTransferFrom(address _token, address _from, address _to, uint256 _value) {
    // 0x23b872dd is the selector for "transferFrom(address,address,uint256)"
    (bool success, bytes memory data) = _token.call(
        abi.encodeWithSelector(0x23b872dd, _from, _to, _value)
    );

    bool condition = success && (data.length == 0 || abi.decode(data, (bool)));

    if (!condition) {
        revert SafeTransferFromError();
    }
}

/**
 * @notice Safely transfer the native token to the account
 * @param _to The native token transfer recipient address
 * @param _value The native token transfer amount
 */
function safeTransferNative(address _to, uint256 _value) {
    (bool success, ) = _to.call{ value: _value }(new bytes(0));

    if (!success) {
        revert SafeTransferNativeError();
    }
}

contracts/interfaces/IActionDataStructures.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

import { IAssetDataStructures } from './IAssetDataStructures.sol';

/**
 * @title IActionDataStructures
 * @notice Action data structure declarations
 */
interface IActionDataStructures is IAssetDataStructures {
    /**
     * @notice Cross-chain action data structure
     * @param gatewayType The numeric type of the cross-chain gateway
     * @param assetType The numeric type of the asset
     * @param sourceTokenAddress The address of the input token on the source chain
     * @param sourceSwapInfo The data for the source chain swap
     * @param minTargetAmountLD The minimum target amount (source chain local decimals)
     * @param targetChainId The action target chain ID
     * @param targetTokenAddress The address of the output token on the destination chain
     * @param targetSwapInfo The data for the target chain swap
     * @param targetRecipient The address of the recipient on the target chain
     * @param targetGasReserveOverride The target gas reserve override value
     * @param gatewaySettings The gateway-specific settings data
     */
    struct Action {
        uint256 gatewayType;
        uint256 assetType;
        address sourceTokenAddress;
        SwapInfo sourceSwapInfo;
        uint256 minTargetAmountLD;
        uint256 targetChainId;
        address targetTokenAddress;
        SwapInfo targetSwapInfo;
        address targetRecipient;
        uint256 targetGasReserveOverride;
        bytes gatewaySettings;
    }

    /**
     * @notice Token swap data structure
     * @param fromAmount The quantity of the token
     * @param routerType The numeric type of the swap router
     * @param routerData The data for the swap router call
     */
    struct SwapInfo {
        uint256 fromAmount;
        uint256 routerType;
        bytes routerData;
    }

    /**
     * @notice Cross-chain message data structure
     * @param actionId The unique identifier of the cross-chain action
     * @param sourceSender The address of the sender on the source chain
     * @param gatewayType The numeric type of the gateway
     * @param assetType The numeric type of the asset
     * @param targetTokenAddress The address of the output token on the target chain
     * @param targetSwapInfo The data for the target chain swap
     * @param targetRecipient The address of the recipient on the target chain
     * @param targetGasReserveOverride The target gas reserve override value
     */
    struct TargetMessage {
        uint256 actionId;
        address sourceSender;
        uint256 gatewayType;
        uint256 assetType;
        address targetTokenAddress;
        SwapInfo targetSwapInfo;
        address targetRecipient;
        uint256 targetGasReserveOverride;
    }

    /**
     * @notice Token amount data structure
     * @param tokenAddress The address of the token
     * @param amount The amount of the token
     */
    struct TokenAmountData {
        address tokenAddress;
        uint256 amount;
    }
}

contracts/interfaces/IAssetDataStructures.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

/**
 * @title IAssetDataStructures
 * @notice Token data structure declarations
 */
interface IAssetDataStructures {
    /**
     * @notice Asset amount data structure
     * @param assetType The type of the asset
     * @param amount The amount of the asset
     */
    struct AssetAmountData {
        uint256 assetType;
        uint256 amount;
    }
}

contracts/interfaces/ITokenBalance.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

/**
 * @title ITokenBalance
 * @notice Token balance interface
 */
interface ITokenBalance {
    /**
     * @notice Getter of the token balance by the account
     * @param _account The account address
     * @return Token balance
     */
    function balanceOf(address _account) external view returns (uint256);
}

contracts/interfaces/ITokenDecimals.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

/**
 * @title ITokenDecimals
 * @notice Token decimals interface
 */
interface ITokenDecimals {
    /**
     * @notice Getter of the token decimals
     * @return Token decimals
     */
    function decimals() external view returns (uint8);
}

contracts/roles/ManagerRole.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

import { Ownable } from '@openzeppelin/contracts/access/Ownable.sol';
import { RoleBearers } from './RoleBearers.sol';

/**
 * @title ManagerRole
 * @notice Base contract that implements the Manager role.
 * The manager role is a high-permission role for core team members only.
 * Managers can set vaults and routers addresses, fees, cross-chain protocols,
 * and other parameters for Interchain (cross-chain) swaps and single-network swaps.
 * Please note, the manager role is unique for every contract,
 * hence different addresses may be assigned as managers for different contracts.
 */
abstract contract ManagerRole is Ownable, RoleBearers {
    bytes32 private constant ROLE_KEY = keccak256('Manager');

    /**
     * @notice Emitted when the Manager role status for the account is updated
     * @param account The account address
     * @param value The Manager role status flag
     */
    event SetManager(address indexed account, bool indexed value);

    /**
     * @notice Emitted when the Manager role status for the account is renounced
     * @param account The account address
     */
    event RenounceManagerRole(address indexed account);

    /**
     * @notice Emitted when the caller is not a Manager role bearer
     */
    error OnlyManagerError();

    /**
     * @dev Modifier to check if the caller is a Manager role bearer
     */
    modifier onlyManager() {
        if (!isManager(msg.sender)) {
            revert OnlyManagerError();
        }

        _;
    }

    /**
     * @notice Updates the Manager role status for the account
     * @param _account The account address
     * @param _value The Manager role status flag
     */
    function setManager(address _account, bool _value) public onlyOwner {
        _setRoleBearer(ROLE_KEY, _account, _value);

        emit SetManager(_account, _value);
    }

    /**
     * @notice Renounces the Manager role
     */
    function renounceManagerRole() external onlyManager {
        _setRoleBearer(ROLE_KEY, msg.sender, false);

        emit RenounceManagerRole(msg.sender);
    }

    /**
     * @notice Getter of the Manager role bearer count
     * @return The Manager role bearer count
     */
    function managerCount() external view returns (uint256) {
        return _roleBearerCount(ROLE_KEY);
    }

    /**
     * @notice Getter of the complete list of the Manager role bearers
     * @return The complete list of the Manager role bearers
     */
    function fullManagerList() external view returns (address[] memory) {
        return _fullRoleBearerList(ROLE_KEY);
    }

    /**
     * @notice Getter of the Manager role bearer status
     * @param _account The account address
     */
    function isManager(address _account) public view returns (bool) {
        return _isRoleBearer(ROLE_KEY, _account);
    }

    function _initRoles(
        address _owner,
        address[] memory _managers,
        bool _addOwnerToManagers
    ) internal {
        address ownerAddress = _owner == address(0) ? msg.sender : _owner;

        for (uint256 index; index < _managers.length; index++) {
            setManager(_managers[index], true);
        }

        if (_addOwnerToManagers && !isManager(ownerAddress)) {
            setManager(ownerAddress, true);
        }

        if (ownerAddress != msg.sender) {
            transferOwnership(ownerAddress);
        }
    }
}

contracts/roles/RoleBearers.sol

// SPDX-License-Identifier: AGPL-3.0-only

pragma solidity 0.8.22;

import '../Constants.sol' as Constants;
import '../DataStructures.sol' as DataStructures;

/**
 * @title RoleBearers
 * @notice Base contract that implements role-based access control
 * @dev A custom implementation providing full role bearer lists
 */
abstract contract RoleBearers {
    mapping(bytes32 /*roleKey*/ => address[] /*roleBearers*/) private roleBearerTable;
    mapping(bytes32 /*roleKey*/ => mapping(address /*account*/ => DataStructures.OptionalValue /*status*/))
        private roleBearerIndexTable;

    function _setRoleBearer(bytes32 _roleKey, address _account, bool _value) internal {
        DataStructures.uniqueAddressListUpdate(
            roleBearerTable[_roleKey],
            roleBearerIndexTable[_roleKey],
            _account,
            _value,
            Constants.LIST_SIZE_LIMIT_DEFAULT
        );
    }

    function _isRoleBearer(bytes32 _roleKey, address _account) internal view returns (bool) {
        return roleBearerIndexTable[_roleKey][_account].isSet;
    }

    function _roleBearerCount(bytes32 _roleKey) internal view returns (uint256) {
        return roleBearerTable[_roleKey].length;
    }

    function _fullRoleBearerList(bytes32 _roleKey) internal view returns (address[] memory) {
        return roleBearerTable[_roleKey];
    }
}
Compiler settingsShow
{
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.