Перейти к содержимому
Проверенный контрактТочноеMIT

UsdcForwarder

Адрес0xe33da59b341e03637a13c3b816c7256b1a8d338a
Баланс

0 ETH

 

Транзакций

33

 

Компилятор

solc 0.8.38

 

Тот же код

ещё 1 контракт

 

Подробности

Компилятор
solc 0.8.38+commit.1835d247
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
prague
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 454 526
Транзакция создания
0xca3df87d86…452f87d8c6

UsdcForwarder.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

interface IERC20 {
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
}

interface ITokenMessengerV2 {
    function depositForBurn(
        uint256 amount,
        uint32 destinationDomain,
        bytes32 mintRecipient,
        address burnToken,
        bytes32 destinationCaller,
        uint256 maxFee,
        uint32 minFinalityThreshold
    ) external;
}

interface IMessageTransmitterV2 {
    function receiveMessage(bytes calldata message, bytes calldata attestation) external returns (bool);
    /// 1 = сообщение с этим nonce уже получено
    function usedNonces(bytes32 nonce) external view returns (uint256);
}

interface ILighter {
    function deposit(address _to, uint16 _assetIndex, uint8 _routeType, uint256 _amount) external payable;
}

interface ICoreDepositWallet {
    /// списывает USDC с msg.sender, зачисляет recipient на HyperCore
    function depositFor(address recipient, uint256 amount, uint32 destinationDex) external;
}

/// @notice Один код на Ethereum, Arbitrum и HyperEVM, по контракту на сеть.
///         caller1 только запускает, деньги всегда идут source2 -> source2:
///           bridge           source2 -> CCTP -> source2 в другой разрешённой сети
///           claimAndDeposit  CCTP claim (минтит на source2) и/или source2 -> биржа этой сети
///         Биржа сети: Ethereum = Lighter, HyperEVM = HyperCore perp, Arbitrum = Hyperliquid через
///         Bridge2 (Variational отдельно, он сам забирает USDC с source2 по REST-заявке).
///         Всё, что меняется редко, зашито: поменялось = новый деплой.
contract UsdcForwarder {
    address public immutable caller1; // only this address can trigger
    address public immutable source2; // token source and recipient everywhere (must approve this contract)
    address public immutable usdc;    // USDC текущей сети, по chainid

    // CCTP V2, одинаковые адреса во всех EVM-сетях
    address public constant TOKEN_MESSENGER = 0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d;
    address public constant MESSAGE_TRANSMITTER = 0x81D40F21F12A8F0E3252Bccb954D722d4c464B64;

    // разрешённые сети назначения (CCTP domain), в свою сеть TokenMessenger не пустит сам
    uint32 public constant ETHEREUM_DOMAIN = 0;
    uint32 public constant ARBITRUM_DOMAIN = 3;
    uint32 public constant HYPEREVM_DOMAIN = 19;

    // биржи
    address public constant LIGHTER = 0x3B4D794a66304F130a4Db8F2551B0070dfCf5ca7;             // Ethereum
    address public constant CORE_DEPOSIT_WALLET = 0x6B9E773128f453f5c2C60935Ee2DE2CBc5390A24; // HyperEVM
    address public constant HL_BRIDGE2 = 0x2Df1c51E09aECF9cacB7bc98cB1742757f163dF7;          // Arbitrum

    // Bridge2 зачисляет на HyperCore тому, кто стоит from в переводе USDC, получателя у него нет.
    // поэтому только прямой transferFrom source2 -> мост: через контракт зачислилось бы контракту.
    // депозит меньше минимума HyperCore молча теряет, а on-chain часть при этом успешна
    uint256 public constant HL_BRIDGE2_MIN = 5_000_000; // 5 USDC

    // fast: Circle списывает свою фактическую комиссию, maxFee только потолок
    // (сейчас Ethereum 1, Arbitrum 1.4, HyperEVM 0 bps)
    uint256 public constant FAST_FEE_BPS = 2;

    constructor(address _caller1, address _source2) {
        require(_caller1 != address(0) && _source2 != address(0), "zero");
        caller1 = _caller1;
        source2 = _source2;

        if (block.chainid == 1) usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
        else if (block.chainid == 42161) usdc = 0xaf88d065e77c8cC2239327C5EDb3A432268e5831;
        else if (block.chainid == 999) usdc = 0xb88339CB7199b77E23DB6E890353E22632Ba630f;
        else revert("unsupported chain");
    }

    modifier onlyCaller1() {
        require(msg.sender == caller1, "not caller1");
        _;
    }

    /// @notice Withdraw any ERC20 stuck in this contract to source2
    function withdrawERC20(address _token) external onlyCaller1 {
        uint256 bal = IERC20(_token).balanceOf(address(this));
        require(IERC20(_token).transfer(source2, bal), "transfer failed");
    }

    /// @notice source2 -> CCTP burn -> mint на source2 в _destinationDomain
    /// @param _amount USDC amount (6 decimals)
    /// @param _destinationDomain ETHEREUM_DOMAIN, ARBITRUM_DOMAIN или HYPEREVM_DOMAIN
    /// @param _fast true = fast (комиссия Circle), false = slow (бесплатно, ждать финальности)
    function bridge(uint256 _amount, uint32 _destinationDomain, bool _fast) external onlyCaller1 {
        require(
            _destinationDomain == ETHEREUM_DOMAIN || _destinationDomain == ARBITRUM_DOMAIN || _destinationDomain == HYPEREVM_DOMAIN,
            "domain not allowed"
        );

        require(IERC20(usdc).transferFrom(source2, address(this), _amount), "pull failed");
        require(IERC20(usdc).approve(TOKEN_MESSENGER, _amount), "approve failed");

        uint256 maxFee = _fast ? (_amount * FAST_FEE_BPS + 9_999) / 10_000 : 0;
        uint32 minFinalityThreshold = _fast ? 1_000 : 2_000;

        ITokenMessengerV2(TOKEN_MESSENGER).depositForBurn(
            _amount,
            _destinationDomain,
            bytes32(uint256(uint160(source2))),
            usdc,
            bytes32(0),
            maxFee,
            minFinalityThreshold
        );
    }

    /// @notice CCTP claim и/или депозит source2 -> биржа этой сети, каждый шаг необязателен
    /// @param _message CCTP message, пустой = claim пропускаем. уже полученное (claim сделал кто-то
    ///        другой, destinationCaller у нас 0) тоже пропускаем, а не ревертим
    /// @param _attestation Iris attestation к _message
    /// @param _depositAmount сколько депозитим на биржу, 0 = депозит пропускаем
    function claimAndDeposit(bytes calldata _message, bytes calldata _attestation, uint256 _depositAmount) external onlyCaller1 {
        // nonce в сообщении CCTP V2: version(4) | sourceDomain(4) | destinationDomain(4) | nonce(32)
        if (_message.length != 0 && IMessageTransmitterV2(MESSAGE_TRANSMITTER).usedNonces(bytes32(_message[12:44])) == 0) {
            require(IMessageTransmitterV2(MESSAGE_TRANSMITTER).receiveMessage(_message, _attestation), "claim failed");
        }

        if (_depositAmount != 0) {
            if (block.chainid == 42161) {
                require(_depositAmount >= HL_BRIDGE2_MIN, "below hl minimum");
                require(IERC20(usdc).transferFrom(source2, HL_BRIDGE2, _depositAmount), "pull failed");
            } else if (block.chainid == 1) {
                require(IERC20(usdc).transferFrom(source2, address(this), _depositAmount), "pull failed");
                require(IERC20(usdc).approve(LIGHTER, _depositAmount), "approve failed");
                ILighter(LIGHTER).deposit(source2, 3, 0, _depositAmount);
            } else {
                // HyperEVM, других сетей конструктор не пускает
                require(IERC20(usdc).transferFrom(source2, address(this), _depositAmount), "pull failed");
                require(IERC20(usdc).approve(CORE_DEPOSIT_WALLET, _depositAmount), "approve failed");
                ICoreDepositWallet(CORE_DEPOSIT_WALLET).depositFor(source2, _depositAmount, 0);
            }
        }
    }
}
Настройки компилятораПоказать
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague"
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.