Skip to content
Verified contractExactMIT

USDCBatchDistributor

Address0x0316c618e2f13b63f9708a1e334b6ce36561f736
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,352,100
Creation transaction
0x6df741e016…d19aac7f07

src/USDCBatchDistributor.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

/// @notice The USDC functions this contract calls.
interface IUSDC {
    function decimals() external view returns (uint8);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 value) external returns (bool);
    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external;
}

/// @title USDC Batch Distributor
/// @author JDawg287
/// @notice Pays many recipients in USDC in a single transaction, from the caller's own balance.
///
///         The caller passes a batch and its total. The contract pulls the total from the caller once, sends each
///         recipient their amount, and checks that its own USDC balance ends exactly where it started. Three ways in:
///         - `distribute`: the caller has approved this contract beforehand. Any failed transfer reverts the batch.
///         - `distributeWithPermit`: same, but the approval is a signed EIP-2612 permit sent in the same transaction.
///         - `distributeAllowFailure`: a recipient that cannot be paid (e.g. blacklisted) is skipped instead.
///           Skipped amounts are refunded to the caller in one transfer, and each skip is logged.
///
///         Batch format: one 32-byte word per recipient, `(uint256(uint160(to)) << 96) | amount`. The recipient is in
///         the top 160 bits and the amount in the bottom 96 bits, which halves calldata compared with separate arrays.
///
/// @dev    - No owner, no upgrades, no admin functions, no storage. It only ever moves the caller's own USDC.
///         - `total` is not computed on-chain, and a wrong one always reverts. Too high leaves USDC behind, and the
///           balance check reverts with `BalanceChanged`. Too low runs out of USDC part-way (USDC's own error), or,
///           if this contract already holds USDC, dips into it and the balance check reverts.
///         - The `bool` returned by USDC's `transfer` / `transferFrom` is not checked. Every FiatToken version
///           (v1.0.0 to v2.2, and NativeFiatTokenV2_2) returns true or reverts. If a future upgrade made a payout
///           return false without moving funds, the USDC would stay here and the balance check would revert. If the
///           pull and every payout returned false, nothing would move and no funds would be lost.
///         - In `distribute` and `distributeWithPermit`, a failed transfer reverts with USDC's own error, unchanged.
///         - Permit: a failed permit (already used, e.g. front-run; wrong amount; expired) is ignored and the caller's
///           existing allowance is used; with none, the pull reverts and nothing moves. Signers should use a short
///           deadline: an unused signature stays valid until then, and anyone can submit it to USDC, which overwrites
///           the caller's allowance for this contract (griefing, not theft). A deadline of type(uint256).max is
///           rejected. A successful permit sets the allowance to `total` rather than adding to it, so any standing
///           allowance for this contract is replaced and then used up by the pull. Only 65-byte (v, r, s)
///           signatures are accepted. Smart wallets that need a different signature, and EIP-7702 wallets whose
///           delegate does not implement ERC-1271, should use `approve` + `distribute`.
///         - `TransferFailed` logs only the entry's index. The recipient and amount are in the batch at that index.
///         - Never send USDC to this contract directly. Nothing can withdraw it, so it is locked forever.
///         - An entry that pays this contract itself leaves the amount here, so the balance check reverts the whole
///           batch, even in `distributeAllowFailure`.
///         - The payment loops are written in inline assembly: one reused call buffer, a pointer walk over calldata,
///           and indexes worked out only when needed.
contract USDCBatchDistributor {
    // ---------------------------------------------------------------------
    // Errors
    // ---------------------------------------------------------------------

    /// @notice The USDC address given to the constructor is address(0).
    error ZeroAddress();
    /// @notice The USDC address given to the constructor has no contract code.
    error NotAContract();
    /// @notice The token at the USDC address does not report 6 decimals.
    error WrongDecimals();

    /// @notice The batch has no entries.
    error EmptyBatch();
    /// @notice `total` is 0.
    error ZeroTotal();

    /// @notice This contract's USDC balance after the batch differs from before it.
    error BalanceChanged();

    /// @notice The permit deadline is type(uint256).max.
    error PermitNeverExpires();

    // ---------------------------------------------------------------------
    // Events
    // ---------------------------------------------------------------------

    /// @notice A batch was paid out.
    /// @param sender Whose USDC was distributed.
    /// @param recipients Number of entries paid.
    /// @param total Sum paid, in USDC base units (6 decimals).
    event Distributed(address indexed sender, uint256 recipients, uint256 total);

    /// @notice Entry `index` could not be paid and its amount was refunded to the sender.
    /// @param index Position of the entry in the batch.
    event TransferFailed(uint256 index);

    // ---------------------------------------------------------------------
    // Constants and immutables
    // ---------------------------------------------------------------------

    /// @dev Number of low bits in a batch entry that hold the amount.
    uint256 private constant AMOUNT_BITS = 96;
    /// @dev 96 one-bits, (1 << AMOUNT_BITS) - 1. A literal so inline assembly can use it.
    uint256 private constant AMOUNT_MASK = 0xffffffffffffffffffffffff;

    /// @notice The USDC token this distributor pays out. Set once at deployment.
    address public immutable USDC;

    // ---------------------------------------------------------------------
    // Constructor
    // ---------------------------------------------------------------------

    /// @notice Sets the USDC token after checking it is a contract with 6 decimals.
    /// @param usdc Address of the native USDC contract on this chain.
    constructor(address usdc) {
        if (usdc == address(0)) revert ZeroAddress();
        if (usdc.code.length == 0) revert NotAContract();
        if (IUSDC(usdc).decimals() != 6) revert WrongDecimals();

        USDC = usdc;
    }

    // ---------------------------------------------------------------------
    // Distribution
    // ---------------------------------------------------------------------

    /// @notice Pays every entry in `batch` from the caller's USDC, using the caller's existing approval.
    /// @param batch One word per recipient: `(uint256(uint160(to)) << 96) | amount`.
    /// @param total Sum of all amounts in `batch`.
    function distribute(bytes32[] calldata batch, uint256 total) external {
        _pullAndPay(batch, total, false);
    }

    /// @notice Approves this contract with an EIP-2612 permit, then pays every entry in `batch` from the caller's USDC.
    /// @param batch One word per recipient: `(uint256(uint160(to)) << 96) | amount`.
    /// @param total Sum of all amounts in `batch`. Also the permit value.
    /// @param deadline Last timestamp at which the permit is valid.
    /// @param v Signature recovery byte.
    /// @param r Signature first half.
    /// @param s Signature second half.
    function distributeWithPermit(
        bytes32[] calldata batch,
        uint256 total,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external {
        if (deadline == type(uint256).max) revert PermitNeverExpires();

        try IUSDC(USDC).permit(msg.sender, address(this), total, deadline, v, r, s) {} catch {}

        _pullAndPay(batch, total, false);
    }

    /// @notice Pays every entry in `batch` that can be paid, skips the rest, and refunds the skipped amounts to the
    ///         caller.
    /// @param batch One word per recipient: `(uint256(uint160(to)) << 96) | amount`.
    /// @param total Sum of all amounts in `batch`.
    /// @return failedTotal Sum of the skipped amounts.
    function distributeAllowFailure(bytes32[] calldata batch, uint256 total) external returns (uint256 failedTotal) {
        failedTotal = _pullAndPay(batch, total, true);
    }

    /// @notice Pulls `total` from the caller, pays the batch, refunds skipped amounts, and checks this contract's
    ///         balance is unchanged.
    /// @param batch The packed entries to pay.
    /// @param total Amount to pull from the caller.
    /// @param allowFailure Whether a failed transfer is skipped (true) or reverts the batch (false).
    /// @return failedTotal Sum of the skipped amounts.
    function _pullAndPay(bytes32[] calldata batch, uint256 total, bool allowFailure)
        private
        returns (uint256 failedTotal)
    {
        if (batch.length == 0) revert EmptyBatch();
        if (total == 0) revert ZeroTotal();

        IUSDC usdc = IUSDC(USDC);

        uint256 balanceBefore = usdc.balanceOf(address(this));

        // forge-lint: disable-next-line(erc20-unchecked-transfer)
        usdc.transferFrom(msg.sender, address(this), total);

        uint256 failedCount = 0;
        if (allowFailure) {
            (failedTotal, failedCount) = _payAllowingFailure(batch);
        } else {
            _payAll(batch);
        }

        if (failedTotal != 0) {
            // forge-lint: disable-next-line(erc20-unchecked-transfer)
            usdc.transfer(msg.sender, failedTotal);
        }

        if (usdc.balanceOf(address(this)) != balanceBefore) revert BalanceChanged();

        emit Distributed(msg.sender, batch.length - failedCount, total - failedTotal);
    }

    // ---------------------------------------------------------------------
    // Hot loops (assembly)
    // ---------------------------------------------------------------------

    /// @notice Pays every entry from this contract's balance, reverting with USDC's error if any transfer fails.
    /// @param batch The packed entries to pay.
    function _payAll(bytes32[] calldata batch) private {
        address usdc = USDC;
        bytes4 transferSelector = IUSDC.transfer.selector;

        assembly ("memory-safe") {
            // One 68-byte call buffer in free memory, reused for every transfer: selector | to | amount.
            let buffer := mload(0x40)
            mstore(buffer, transferSelector)

            let end := add(batch.offset, shl(5, batch.length))
            for { let p := batch.offset } lt(p, end) { p := add(p, 0x20) } {
                let entry := calldataload(p)
                mstore(add(buffer, 0x04), shr(AMOUNT_BITS, entry))
                mstore(add(buffer, 0x24), and(entry, AMOUNT_MASK))

                if iszero(call(gas(), usdc, 0, buffer, 0x44, 0x00, 0x00)) {
                    returndatacopy(buffer, 0x00, returndatasize())
                    revert(buffer, returndatasize())
                }
            }
        }
    }

    /// @notice Pays every entry it can from this contract's balance, emitting `TransferFailed` for each one it skips.
    /// @param batch The packed entries to pay.
    /// @return failedTotal Sum of the skipped amounts.
    /// @return failedCount Number of skipped entries.
    function _payAllowingFailure(bytes32[] calldata batch) private returns (uint256 failedTotal, uint256 failedCount) {
        address usdc = USDC;
        bytes4 transferSelector = IUSDC.transfer.selector;
        bytes32 transferFailedTopic = TransferFailed.selector;

        assembly ("memory-safe") {
            let buffer := mload(0x40)
            mstore(buffer, transferSelector)

            let start := batch.offset
            let end := add(start, shl(5, batch.length))
            for { let p := start } lt(p, end) { p := add(p, 0x20) } {
                let entry := calldataload(p)
                let amount := and(entry, AMOUNT_MASK)
                mstore(add(buffer, 0x04), shr(AMOUNT_BITS, entry))
                mstore(add(buffer, 0x24), amount)

                if iszero(call(gas(), usdc, 0, buffer, 0x44, 0x00, 0x00)) {
                    failedTotal := add(failedTotal, amount)
                    failedCount := add(failedCount, 1)

                    // emit TransferFailed(index)
                    mstore(0x00, shr(5, sub(p, start)))
                    log1(0x00, 0x20, transferFailedTopic)
                }
            }
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "forge-std/=dependencies/forge-std-1.17.0/src/",
    "forge-std-1.17.0/=dependencies/forge-std-1.17.0/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.