Verified contractExactMIT
MassPayoutsUnsafe
Address0x765a0cd00e07c23d1f760bdc794940967bc6ccc7
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,398,363
- Creation transaction
- 0x14c37ebde7…14b5473269
10 files
- contracts/MassPayoutsUnsafe.solmain1.17 KB
- @openzeppelin/contracts/access/Ownable.sol3.1 KB
- @openzeppelin/contracts/access/Ownable2Step.sol2.48 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/utils/Context.sol963 B
- @openzeppelin/contracts/utils/Pausable.sol2.71 KB
- @openzeppelin/contracts/utils/ReentrancyGuard.sol4.77 KB
- @openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- contracts/MassPayoutsBase.sol21 KB
- contracts/SafeTransferHelper.sol1.53 KB
contracts/MassPayoutsUnsafe.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "./MassPayoutsBase.sol";
/// @title MassPayoutsUnsafe — batch USDT payouts without sender whitelist.
/// @notice Anyone can call batchPayout.
/// Use when sender restriction is not needed.
contract MassPayoutsUnsafe is MassPayoutsBase {
// ── Constructor ──────────────────────────────────────────────────────
constructor(
address _usdt,
address _commissionWallet,
uint256 _commissionBps,
uint256 _minimalCommission,
uint256 _perTransferCommission
)
MassPayoutsBase(_usdt, _commissionWallet, _commissionBps, _minimalCommission, _perTransferCommission)
Ownable(msg.sender)
{}
// ── Authorization ───────────────────────────────────────────────────
/// @dev No restriction — anyone can send payouts.
function _checkSenderAuthorized() internal view override {
// open access
}
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../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.
*
* The initial owner is set to the address provided by the deployer. 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;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @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 {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling 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 {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_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/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../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 {
bool private _paused;
/**
* @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);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @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 {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @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/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @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 EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* 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].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// 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;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = 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();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
contracts/MassPayoutsBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./SafeTransferHelper.sol";
/// @title MassPayoutsBase — shared logic for batch USDT ERC-20 payouts (Ethereum / BSC).
/// @notice Pull-push model: one transferFrom pulls funds to the contract,
/// then individual transfers push to each recipient + commission.
/// Contract never holds funds (no custody).
abstract contract MassPayoutsBase is Ownable2Step, Pausable, ReentrancyGuard {
// ── Immutables ──────────────────────────────────────────────────────
/// @notice Payout token. Unlike TRON (address baked into the build), EVM networks
/// differ, so the token is a constructor argument fixed for the contract's lifetime.
address public immutable usdt;
// ── State ───────────────────────────────────────────────────────────
address public commissionWallet;
/// @notice Percentage commission rate in basis points: commission = total * commissionBps / BPS_DENOM + ...
/// Defaults to 0 (percentage disabled). Set per deployment via setCommissionBps (owner).
/// Capped at BPS_DENOM (100%). Was the compile-time constant COMMISSION_BPS = 25 (0.25%).
uint256 public commissionBps;
/// @notice Commission floor in token units: commission = max(total * commissionBps / denom + perTransferCommission * delivered, minimalCommission).
/// Defaults to 0 (pure percentage). Set per deployment/network — token decimals differ
/// (USDT: 6 on Ethereum, 18 on BSC).
uint256 public minimalCommission;
/// @notice Flat fee charged per successfully delivered recipient, in token units:
/// commission = max(total * commissionBps / denom + perTransferCommission * delivered, minimalCommission),
/// where `delivered` is the number of recipients that actually received their payout.
/// Defaults to 0. A batch of 50 recipients with 48 delivered is charged the fee 48 times;
/// the 2 failed transfers are refunded and carry no fee. The total (percentage + per-transfer)
/// is split with the partner like the rest of the commission.
uint256 public perTransferCommission;
// ── Constants ────────────────────────────────────────────────────────
uint256 public constant BPS_DENOM = 10_000;
uint256 public constant MAX_BATCH_SIZE = 100;
// ── White-label partners ─────────────────────────────────────────────
struct Partner {
bool active;
uint16 shareBps; // share of commission going to the partner
}
mapping(address => Partner) private _partners;
// ── Errors ───────────────────────────────────────────────────────────
error ZeroAddress();
error TokenNotContract();
error InvalidArrayLength();
error BatchTooLarge();
error EmptyBatch();
error ZeroAmount();
error InvalidPartnerShare();
error InvalidCommissionBps();
error PartnerIsCommissionWallet();
error NothingToWithdraw();
error NativeTransferFailed();
// ── Events ───────────────────────────────────────────────────────────
event PartnerSet(address indexed partner, uint16 shareBps, bool active);
event CommissionBpsChanged(uint256 oldValue, uint256 newValue);
event MinimalCommissionChanged(uint256 oldValue, uint256 newValue);
event PerTransferCommissionChanged(uint256 oldValue, uint256 newValue);
event BatchPayout(
address indexed sender,
uint256 total,
uint256 commission,
uint256 partnerShare,
uint256 count,
address indexed whiteLabel
);
event PayoutFailed(address[] recipients, uint256[] amounts);
event RefundSent(address indexed sender, uint256 amount);
event PartnerNotFound(address indexed whiteLabel);
event CommissionWalletChanged(address indexed oldWallet, address indexed newWallet);
event CommissionTransferFailed(address indexed wallet, uint256 amount);
event EmergencyWithdraw(address indexed token, address indexed to, uint256 amount);
// ── Constructor ──────────────────────────────────────────────────────
/// @param _usdt Payout token (USDT of the target network).
/// @param _commissionWallet Wallet that receives the platform commission.
/// @param _commissionBps Initial percentage rate in basis points (0 disables it, max BPS_DENOM).
/// @param _minimalCommission Initial commission floor in token units (0 disables the floor).
/// @param _perTransferCommission Initial flat fee per delivered recipient in token units (0 disables it).
/// @dev The three commission params are also mutable post-deploy via their setters; passing them
/// here lets a deployment configure commission in a single transaction.
constructor(
address _usdt,
address _commissionWallet,
uint256 _commissionBps,
uint256 _minimalCommission,
uint256 _perTransferCommission
) {
if (_usdt == address(0)) revert ZeroAddress();
// A codeless token address would make every transfer a silent no-op success
// (raw call to an EOA returns success with empty data — indistinguishable from
// non-bool USDT), so a typo in the token address must fail the deployment.
if (_usdt.code.length == 0) revert TokenNotContract();
if (_commissionWallet == address(0)) revert ZeroAddress();
// Mirror setCommissionBps' cap so an out-of-range initial rate reverts the deploy
// rather than producing a mis-configured contract.
if (_commissionBps > BPS_DENOM) revert InvalidCommissionBps();
usdt = _usdt;
commissionWallet = _commissionWallet;
commissionBps = _commissionBps;
minimalCommission = _minimalCommission;
perTransferCommission = _perTransferCommission;
// Emit the same change events the setters do, so off-chain indexers pick up a
// non-zero initial config set at deploy time (skip the no-op 0 → 0 transitions).
if (_commissionBps != 0) emit CommissionBpsChanged(0, _commissionBps);
if (_minimalCommission != 0) emit MinimalCommissionChanged(0, _minimalCommission);
if (_perTransferCommission != 0) emit PerTransferCommissionChanged(0, _perTransferCommission);
}
// ── Authorization hook (overridden by children) ─────────────────────
/// @dev Override to enforce sender restrictions. No-op = open access.
function _checkSenderAuthorized() internal view virtual;
// ═══════════════════════════════════════════════════════════════════
// WHITE-LABEL PARTNERS
// ═══════════════════════════════════════════════════════════════════
function setPartner(address partner, uint16 shareBps, bool active) external onlyOwner {
if (partner == address(0)) revert ZeroAddress();
if (partner == commissionWallet) revert PartnerIsCommissionWallet();
if (shareBps > BPS_DENOM) revert InvalidPartnerShare();
_partners[partner] = Partner(active, shareBps);
emit PartnerSet(partner, shareBps, active);
}
function getPartner(address partner) external view returns (bool active, uint16 shareBps) {
Partner memory p = _partners[partner];
return (p.active, p.shareBps);
}
// ═══════════════════════════════════════════════════════════════════
// BATCH PAYOUT
// ═══════════════════════════════════════════════════════════════════
function batchPayout(
address[] calldata recipients,
uint256[] calldata amounts,
address whiteLabel
) external nonReentrant whenNotPaused {
_checkSenderAuthorized();
uint256 count = recipients.length;
if (count != amounts.length) revert InvalidArrayLength();
if (count == 0) revert EmptyBatch();
if (count > MAX_BATCH_SIZE) revert BatchTooLarge();
uint256 total = 0;
for (uint256 i = 0; i < count; ) {
if (recipients[i] == address(0)) revert ZeroAddress();
if (amounts[i] == 0) revert ZeroAmount();
total += amounts[i];
unchecked { ++i; }
}
_executePayout(recipients, amounts, total, count, whiteLabel);
}
// ═══════════════════════════════════════════════════════════════════
// ADMIN
// ═══════════════════════════════════════════════════════════════════
function pause() external onlyOwner { _pause(); }
function unpause() external onlyOwner { _unpause(); }
/// @notice Set the percentage commission rate in basis points (0 disables it, max BPS_DENOM = 100%).
function setCommissionBps(uint256 _newValue) external onlyOwner {
if (_newValue > BPS_DENOM) revert InvalidCommissionBps();
uint256 old = commissionBps;
commissionBps = _newValue;
emit CommissionBpsChanged(old, _newValue);
}
/// @notice Set the commission floor (token units). 0 disables the floor.
function setMinimalCommission(uint256 _newValue) external onlyOwner {
uint256 old = minimalCommission;
minimalCommission = _newValue;
emit MinimalCommissionChanged(old, _newValue);
}
/// @notice Set the flat per-delivered-recipient commission (token units). 0 disables it.
function setPerTransferCommission(uint256 _newValue) external onlyOwner {
uint256 old = perTransferCommission;
perTransferCommission = _newValue;
emit PerTransferCommissionChanged(old, _newValue);
}
/// @notice Change the commission wallet address.
function setCommissionWallet(address _newWallet) external onlyOwner {
if (_newWallet == address(0)) revert ZeroAddress();
// Mirror of the setPartner guard: an active partner must not become the
// commission wallet, otherwise it would collect both commission shares and
// could never be deactivated (setPartner reverts for the commission wallet).
if (_partners[_newWallet].active) revert PartnerIsCommissionWallet();
address old = commissionWallet;
commissionWallet = _newWallet;
emit CommissionWalletChanged(old, _newWallet);
}
/// @notice Withdraw any tokens stuck on the contract to a specified address.
/// token == address(0) withdraws the native coin (ETH / BNB): the contract has no
/// receive/fallback, but native value can still be forced in (SELFDESTRUCT in the
/// creating tx, block rewards / withdrawals, pre-deploy sends to the CREATE address)
/// and would otherwise be stuck forever. Same as the native branch of the TRON version.
/// @dev nonReentrant: the native branch hands control to `to`; the lock keeps it from
/// re-entering batchPayout mid-withdrawal (defence in depth — only the owner calls this).
function emergencyWithdraw(address token, address to, uint256 amount) external onlyOwner nonReentrant {
if (to == address(0)) revert ZeroAddress();
if (amount == 0) revert NothingToWithdraw();
if (token == address(0)) {
(bool ok, ) = payable(to).call{value: amount}("");
if (!ok) revert NativeTransferFailed();
} else {
SafeTransferHelper.safeTransfer(token, to, amount);
}
emit EmergencyWithdraw(token, to, amount);
}
// ═══════════════════════════════════════════════════════════════════
// VIEW HELPERS
// ═══════════════════════════════════════════════════════════════════
/// @param total Sum of the payout amounts. @param count Number of recipients that receive them.
function previewCommission(uint256 total, uint256 count) external view returns (uint256 commission) {
commission = _commissionFor(total, count);
}
function previewCommissionSplit(uint256 total, uint256 count, address whiteLabel)
external view returns (uint256 platformCommission, uint256 partnerShare)
{
(, uint16 partnerBps) = _partnerShareBps(whiteLabel);
(platformCommission, partnerShare) = _calcCommission(total, count, partnerBps);
}
// ═══════════════════════════════════════════════════════════════════
// INTERNAL
// ═══════════════════════════════════════════════════════════════════
function _executePayout(
address[] calldata recipients,
uint256[] calldata amounts,
uint256 total,
uint256 count,
address whiteLabel
) private {
uint16 partnerBps = _resolvePartner(whiteLabel);
address token = usdt;
// Pull total + commission assuming every recipient succeeds (the maximum: the per-transfer
// fee applies to all `count` recipients). Any overpull from failed transfers is refunded.
uint256 fullCommission = _commissionFor(total, count);
SafeTransferHelper.safeTransferFrom(token, msg.sender, address(this), total + fullCommission);
// Distribute to recipients, collect failures
(uint256 failedTotal, uint256 failedCount) =
_distributeAndCollectFailures(token, recipients, amounts, count);
// Commission on delivered amount and delivered count, send, refund, emit
_finalizeAndRefund(
token, total, failedTotal, count - failedCount, fullCommission, partnerBps, count, whiteLabel
);
}
function _finalizeAndRefund(
address token,
uint256 total,
uint256 failedTotal,
uint256 successCount,
uint256 fullCommission,
uint16 partnerBps,
uint256 count,
address whiteLabel
) private {
uint256 successTotal = total - failedTotal;
(uint256 platformComm, uint256 partnerShare) = _calcCommission(successTotal, successCount, partnerBps);
(uint256 undeliveredPlatform, uint256 undeliveredPartner) =
_sendCommission(token, platformComm, partnerShare, whiteLabel);
// Undelivered commission (e.g. the commission wallet or partner is blacklisted
// by the token) is refunded to the sender: nobody received it, the sender must
// not pay for nothing, and the contract must hold zero balance after a payout.
uint256 refund = failedTotal + fullCommission - (platformComm + partnerShare)
+ undeliveredPlatform + undeliveredPartner;
if (refund > 0) {
SafeTransferHelper.safeTransfer(token, msg.sender, refund);
emit RefundSent(msg.sender, refund);
}
// The event reports commission amounts actually delivered, not merely charged.
emit BatchPayout(
msg.sender,
successTotal,
platformComm + partnerShare - undeliveredPlatform - undeliveredPartner,
partnerShare - undeliveredPartner,
count,
whiteLabel
);
}
function _sendCommission(address token, uint256 platformCommission, uint256 partnerShare, address whiteLabel)
private returns (uint256 undeliveredPlatform, uint256 undeliveredPartner)
{
if (platformCommission > 0) {
if (!SafeTransferHelper.tryTransfer(token, commissionWallet, platformCommission)) {
emit CommissionTransferFailed(commissionWallet, platformCommission);
undeliveredPlatform = platformCommission;
}
}
if (partnerShare > 0) {
if (!SafeTransferHelper.tryTransfer(token, whiteLabel, partnerShare)) {
emit CommissionTransferFailed(whiteLabel, partnerShare);
undeliveredPartner = partnerShare;
}
}
}
function _distributeAndCollectFailures(
address token,
address[] calldata recipients,
uint256[] calldata amounts,
uint256 count
) private returns (uint256 failedTotal, uint256 failedCount) {
address[] memory failedAddrs = new address[](count);
uint256[] memory failedAmts = new uint256[](count);
for (uint256 i = 0; i < count; ) {
if (!SafeTransferHelper.tryTransfer(token, recipients[i], amounts[i])) {
failedAddrs[failedCount] = recipients[i];
failedAmts[failedCount] = amounts[i];
failedTotal += amounts[i];
unchecked { ++failedCount; }
}
unchecked { ++i; }
}
if (failedCount > 0) {
address[] memory trimAddrs = new address[](failedCount);
uint256[] memory trimAmts = new uint256[](failedCount);
for (uint256 j = 0; j < failedCount; ) {
trimAddrs[j] = failedAddrs[j];
trimAmts[j] = failedAmts[j];
unchecked { ++j; }
}
emit PayoutFailed(trimAddrs, trimAmts);
}
}
/// @dev Single source of truth for partner resolution, shared by the payout path
/// and previewCommissionSplit so the preview can never diverge from execution.
/// `found` is false only for a non-zero address that is not an active partner.
function _partnerShareBps(address whiteLabel) private view returns (bool found, uint16 bps) {
if (whiteLabel == address(0)) return (true, 0);
Partner memory p = _partners[whiteLabel];
if (!p.active) return (false, 0);
return (true, p.shareBps);
}
function _resolvePartner(address whiteLabel) private returns (uint16) {
(bool found, uint16 bps) = _partnerShareBps(whiteLabel);
if (!found) emit PartnerNotFound(whiteLabel);
return bps;
}
/// @dev Commission = percentage + per-transfer fee times the number of delivered recipients,
/// then floored by minimalCommission. Zero total means nothing was (or will be) delivered
/// (deliveredCount is 0 too) — no commission, so a fully failed batch is refunded in full.
function _commissionFor(uint256 total, uint256 deliveredCount) private view returns (uint256) {
if (total == 0) return 0;
uint256 commission = (total * commissionBps) / BPS_DENOM
+ perTransferCommission * deliveredCount;
uint256 floor_ = minimalCommission;
return commission < floor_ ? floor_ : commission;
}
function _calcCommission(uint256 total, uint256 deliveredCount, uint16 partnerBps)
private view returns (uint256 platformComm, uint256 partnerShare)
{
uint256 commission = _commissionFor(total, deliveredCount);
partnerShare = (commission * partnerBps) / BPS_DENOM;
platformComm = commission - partnerShare;
}
}
contracts/SafeTransferHelper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title SafeTransferHelper — safe ERC-20 transfers with non-standard USDT compatibility.
/// @notice Handles tokens that do not return bool from transfer/transferFrom (e.g. Ethereum USDT).
library SafeTransferHelper {
/// @dev Attempts transfer, returns false on failure (does NOT revert).
/// A codeless `token` is a failure: a raw call to it returns success with empty
/// data, which is indistinguishable from a non-bool token like USDT.
function tryTransfer(address token, address to, uint value) internal returns (bool) {
if (token.code.length == 0) return false;
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
return success && (data.length == 0 || abi.decode(data, (bool)));
}
function safeTransfer(address token, address to, uint value) internal {
require(tryTransfer(token, to, value), "SafeTransferHelper: TRANSFER_FAILED");
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
require(token.code.length > 0, "SafeTransferHelper: TRANSFER_FROM_FAILED");
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeTransferHelper: TRANSFER_FROM_FAILED");
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.