批量发送erc20代币

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract BatchTransfer {
    using SafeERC20 for IERC20;

    function transfer(address[] calldata addresses, uint256 amount)
    external
    payable
    {
        uint256 total = amount * addresses.length;
        require(msg.value <= total, "BatchTransfer: value is not equal");
        require(msg.value == total, "BatchTransfer: insufficient funds");

        for (uint256 i = 0; i < addresses.length; ) {
            (bool success, ) = addresses[i].call{value: amount}("");
            require(success, "BatchTransfer: transfer failed");

        unchecked {
            i++;
        }
        }
    }

    function transfer(address[] calldata addresses, uint256[] calldata amounts)
    external
    payable
    {
        require(
            addresses.length == amounts.length,
            "BatchTransfer: array length inconsistent"
        );

        uint256 value = msg.value;

        for (uint256 i = 0; i < addresses.length; ) {
            (bool success, ) = addresses[i].call{value: amounts[i]}("");
            require(success, "BatchTransfer: transfer failed");

        unchecked {
            value -= amounts[i];
            i++;
        }
        }

        require(value == 0, "BatchTransfer: value is not equal");
    }



    function transferToken(
        IERC20 token,
        address[] calldata addresses,
        uint256 amount
    ) external {
        uint256 total = amount * addresses.length;
        require(
            token.balanceOf(msg.sender) >= total,
            "BatchTransfer: insufficient funds"
        );
        require(
            token.allowance(msg.sender, address(this)) >= total,
            "BatchTransfer: insufficient allowance"
        );

        for (uint256 i = 0; i < addresses.length; ) {
            token.safeTransferFrom(msg.sender, addresses[i], amount);

        unchecked {
            i++;
        }
        }
    }

    function transferToken(
        IERC20 token,
        address[] calldata addresses,
        uint256[] calldata amounts
    ) external {
        require(
            addresses.length == amounts.length,
            "BatchTransfer: array length inconsistent"
        );

        for (uint256 i = 0; i < addresses.length; ) {
            token.safeTransferFrom(msg.sender, addresses[i], amounts[i]);

        unchecked {
            i++;
        }
        }
    }

}
需要在erc20代币合约的approve函数授权
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值