HolderDistributor

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "@openzeppelin/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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. 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 {
        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/access/Ownable2Step.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.0;

import "./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.
 *
 * By default, the owner account will be the one that deploys the contract. 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.
     */
    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();
        require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
        _transferOwnership(sender);
    }
}
"
    },
    "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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;
    }

    /**
     * @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 _status == _ENTERED;
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount) external returns (bool);
}
"
    },
    "@openzeppelin/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
"
    },
    "contracts/HolderDistributor.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

/**
* @title HolderDistributor - Fully Automated HYM Proportional Distribution
* @dev Distributes tokens proportionally with automatic update of top holders
* @notice Implemented features:
* - Distribution proportional to balance
* - Monthly distribution automation
* - Automatic daily update of the top holders list
* - Automatic holder tracking
* - Gas optimization with pagination
* - Ready for Gnosis Safe
 */

import '@openzeppelin/contracts/access/Ownable2Step.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';

contract HolderDistributor is Ownable2Step, ReentrancyGuard {
    // --- Timelock para Gnosis Safe ---
    address public timelock;
    event TimelockSet(address indexed oldTimelock, address indexed newTimelock);
  
    modifier onlyGov() { 
        require(msg.sender == owner() || msg.sender == timelock, 'Only owner/timelock'); 
        _; 
    }

    function setTimelock(address newTimelock) public onlyOwner {
        emit TimelockSet(timelock, newTimelock);
        timelock = newTimelock;
    }

    // --- Main settings ---
    IERC20 public hymToken;
    address public vaultAddress;
    uint256 public minHolding = 10_000 * 1e18;
    uint256 public holdingPeriod = 90 days;

    // --- Distribution automation ---
    uint256 public lastDistribution;
    uint256 public distributionInterval = 30 days;
    bool public autoDistributionEnabled = true;

    // --- Top holders automation ---
    uint256 public lastTopHoldersUpdate;
    uint256 public topHoldersUpdateInterval = 1 days;
    bool public autoTopHoldersUpdateEnabled = true;
    uint256 public maxTopHolders = 100;

    // --- Gas tracking for top holders update ---
    uint256 public lastUpdateGasUsed;

    // --- Eligibility control ---
    mapping(address => uint256) public firstReceivedTimestamp;
    mapping(address => bool) public isTrustedCaller;

    // --- Automatic holder tracking ---
    address[] public allHolders; // Complete list of known holders
    mapping(address => bool) public isKnownHolder;
    mapping(address => uint256) public holderIndex; // Index in the allHolders list

    // --- Top holders list (limited and optimized) ---
    address[] public topHolders;
    mapping(address => bool) public isTopHolder;

    // --- Distribution control ---
    struct DistributionRound {
        uint256 timestamp;
        uint256 totalDistributed;
        uint256 totalEligibleHolders;
        uint256 totalEligibleBalance;
    }

    DistributionRound[] public distributionHistory;

    // --- Events ---
    event HolderNotified(address indexed holder);
    event HolderAdded(address indexed holder);
    event HolderRemoved(address indexed holder);
    event TokensDistributed(uint256 totalDistributed, uint256 totalHolders, uint256 totalBalance);
    event ProportionalDistribution(address indexed user, uint256 amount, uint256 userBalance, uint256 totalBalance);
    event TopHoldersUpdated(uint256 count, uint256 gasUsed);
    event AutoTopHoldersUpdateToggled(bool enabled);
    event TopHoldersUpdateIntervalUpdated(uint256 newInterval);
    event MaxTopHoldersUpdated(uint256 newMax);
    event MinHoldingUpdated(uint256 newAmount);
    event HoldingPeriodUpdated(uint256 newPeriod);
    event TokenUpdated(address indexed newToken);
    event VaultUpdated(address indexed newVault);
    event EmergencyWithdraw(address indexed vault, uint256 amount);
    event AutoDistributionToggled(bool enabled);
    event DistributionIntervalUpdated(uint256 newInterval);

    /**
* @dev Constructor for the HolderDistributor contract.
* @param _token HYM token address.
     */
    constructor(address _token) Ownable2Step() {
        require(_token != address(0), 'Invalid token');
        hymToken = IERC20(_token);
        lastDistribution = block.timestamp;
        lastTopHoldersUpdate = block.timestamp;
    }

    /**
* @notice Defines whether an address is a trusted caller for `notifyReceived`.
* @param caller The address to set as trusted.
* @param trusted True to trust, false to not trust.
     */
    function setTrustedCaller(address caller, bool trusted) external onlyGov {
        isTrustedCaller[caller] = trusted;
    }

    /**
     * @notice Notifies that a holder has received tokens (AUTOMATED)
     * @dev This function is called by the HYMToken contract automatically
     * @param holder The address of the holder to be notified.
     */
    function notifyReceived(address holder) external {
        require(
            msg.sender == address(hymToken) || isTrustedCaller[msg.sender],
            'Only token or trusted caller can notify'
        );

        uint256 holderBalance = hymToken.balanceOf(holder);

        // Adds to the known holders list if not already present
        if (!isKnownHolder[holder] && holderBalance > 0) {
            _addHolder(holder);
        }

        // Removes from the list if balance is zero
        if (isKnownHolder[holder] && holderBalance == 0) {
            _removeHolder(holder);
        }

        // Updates eligibility
        if (holderBalance >= minHolding) {
            if (
                firstReceivedTimestamp[holder] == 0 || 
                block.timestamp < firstReceivedTimestamp[holder] + holdingPeriod
            ) {
                firstReceivedTimestamp[holder] = block.timestamp;
                emit HolderNotified(holder);
            }
        } else {
            firstReceivedTimestamp[holder] = 0;
        }
    }

    /**
     * @dev Adds a holder to the known holders list
     * @param holder The address of the holder
     */
    function _addHolder(address holder) internal {
        if (!isKnownHolder[holder]) {
            holderIndex[holder] = allHolders.length;
            allHolders.push(holder);
            isKnownHolder[holder] = true;
            emit HolderAdded(holder);
        }
    }

    /**
     * @dev Removes a holder from the known holders list
     * @param holder The address of the holder
     */
    function _removeHolder(address holder) internal {
        if (isKnownHolder[holder]) {
            uint256 index = holderIndex[holder];
            uint256 lastIndex = allHolders.length - 1;

            // Move the last element to the position of the removed one
            if (index != lastIndex) {
                address lastHolder = allHolders[lastIndex];
                allHolders[index] = lastHolder;
                holderIndex[lastHolder] = index;
            }

            // Remove the last element
            allHolders.pop();
            delete holderIndex[holder];
            isKnownHolder[holder] = false;

            // Remove from the top holders list if present
            if (isTopHolder[holder]) {
                isTopHolder[holder] = false;
            }
            
            emit HolderRemoved(holder);
        }
    }

    /**
     * @notice Automatic update of the top holders list 
     * @dev Can be called by anyone, but respecting the interval
     * MODIFIED FOR TESTING: Cooldown temporarily disabled
     */
    function autoUpdateTopHolders() external {
        require(autoTopHoldersUpdateEnabled, "Auto update disabled");
        // require(
        //     block.timestamp >= lastTopHoldersUpdate + topHoldersUpdateInterval,
        //     "Update interval not reached"
        // );
        
        _updateTopHolders();
    }

    /**
     * @notice Manual update of the top holders list
     * @dev Allows manual update by the owner/timelock
     */
    function manualUpdateTopHolders() external onlyGov {
        _updateTopHolders();
    }

    /**
     * @dev Executes the update of the top holders list
     */
    function _updateTopHolders() internal {
        uint256 gasStart = gasleft();

        // Clears old markings
        for (uint256 i = 0; i < topHolders.length; i++) {
            isTopHolder[topHolders[i]] = false;
        }
        delete topHolders;

        // Creates temporary arrays for sorting
        address[] memory candidates = new address[](allHolders.length);
        uint256[] memory balances = new uint256[](allHolders.length);
        uint256 candidateCount = 0;

        // Collects holders with minimum balance
        for (uint256 i = 0; i < allHolders.length; i++) {
            address holder = allHolders[i];
            uint256 balance = hymToken.balanceOf(holder);

            if (balance >= minHolding) {
                candidates[candidateCount] = holder;
                balances[candidateCount] = balance;
                candidateCount++;
            }
        }

        // Sorts by balance (bubble sort optimized for top N)
        uint256 topCount = candidateCount > maxTopHolders ? maxTopHolders : candidateCount;
        
        for (uint256 i = 0; i < topCount; i++) {
            uint256 maxIndex = i;
            for (uint256 j = i + 1; j < candidateCount; j++) {
                if (balances[j] > balances[maxIndex]) {
                    maxIndex = j;
                }
            }
            
            // Swap
            if (maxIndex != i) {
                (candidates[i], candidates[maxIndex]) = (candidates[maxIndex], candidates[i]);
                (balances[i], balances[maxIndex]) = (balances[maxIndex], balances[i]);
            }

            // Adds to the top holders
            topHolders.push(candidates[i]);
            isTopHolder[candidates[i]] = true;
        }

        lastTopHoldersUpdate = block.timestamp;
        uint256 gasUsed = gasStart - gasleft();
        
        emit TopHoldersUpdated(topHolders.length, gasUsed);
    }

    /**
     * @notice Automatic proportional distribution
     * @dev Automatically sweeps the top holders and distributes proportionally
     * MODIFIED FOR TESTING: Cooldown temporarily disabled
     */
    function autoDistribute() external {
        require(autoDistributionEnabled, "Auto distribution disabled");
        
        // require(block.timestamp >= lastDistribution + distributionInterval, "Distribution interval not reached");
        
        _executeProportionalDistribution();
    }

    /**
     * @notice Manual proportional distribution for a specific list of holders
     * @dev Allows manual distribution with a custom list
     * @param holders List of addresses to consider in the distribution
     */
    function distributeProportional(address[] calldata holders) external onlyGov nonReentrant {
        require(holders.length > 0, "Empty holders list");
        require(holders.length <= 200, "Too many holders");
        
        _executeProportionalDistributionForList(holders);
    }

    /**
     * @dev Executes automatic proportional distribution using top holders
     */
    function _executeProportionalDistribution() internal nonReentrant {
        require(topHolders.length > 0, "No top holders configured");
        
        _executeProportionalDistributionForList(topHolders);
    }

    /**
     * @dev Executes proportional distribution for a specific list
     * @param holders List of holders for distribution
     */
    function _executeProportionalDistributionForList(address[] memory holders) internal {
        uint256 totalToDistribute = hymToken.balanceOf(address(this));
        require(totalToDistribute > 0, "Nothing to distribute");

        // First pass: calculate total eligible and total balance
        uint256 totalEligibleBalance = 0;
        uint256 eligibleCount = 0;
        
        for (uint256 i = 0; i < holders.length; i++) {
            address holder = holders[i];
            if (isEligible(holder)) {
                uint256 holderBalance = hymToken.balanceOf(holder);
                totalEligibleBalance += holderBalance;
                eligibleCount++;
            }
        }

        require(eligibleCount > 0, "No eligible holders");
        require(totalEligibleBalance > 0, "No eligible balance");

        // Second pass: distribute proportionally
        uint256 totalDistributed = 0;
        
        for (uint256 i = 0; i < holders.length; i++) {
            address holder = holders[i];
            if (isEligible(holder)) {
                uint256 holderBalance = hymToken.balanceOf(holder);

                // Calculates proportional distribution
                uint256 holderShare = (totalToDistribute * holderBalance) / totalEligibleBalance;
                
                if (holderShare > 0) {
                    require(hymToken.transfer(holder, holderShare), "Transfer failed");
                    totalDistributed += holderShare;
                    
                    emit ProportionalDistribution(holder, holderShare, holderBalance, totalEligibleBalance);
                }
            }
        }

        // Remainder (if any) goes to the vault
        uint256 remainder = totalToDistribute - totalDistributed;
        if (remainder > 0 && vaultAddress != address(0)) {
            require(hymToken.transfer(vaultAddress, remainder), "Vault transfer failed");
        }

        // Updates history
        lastDistribution = block.timestamp;
        distributionHistory.push(DistributionRound({
            timestamp: block.timestamp,
            totalDistributed: totalDistributed,
            totalEligibleHolders: eligibleCount,
            totalEligibleBalance: totalEligibleBalance
        }));

        emit TokensDistributed(totalDistributed, eligibleCount, totalEligibleBalance);
    }

    /**
     * @notice Top Holder Automation Settings
     */
    function setAutoTopHoldersUpdateEnabled(bool enabled) external onlyGov {
        autoTopHoldersUpdateEnabled = enabled;
        emit AutoTopHoldersUpdateToggled(enabled);
    }

    function setTopHoldersUpdateInterval(uint256 intervalInSeconds) external onlyGov {
        require(intervalInSeconds >= 1 hours, "Minimum interval: 1 hour");
        require(intervalInSeconds <= 7 days, "Maximum interval: 7 days");
        topHoldersUpdateInterval = intervalInSeconds;
        emit TopHoldersUpdateIntervalUpdated(intervalInSeconds);
    }

    function setMaxTopHolders(uint256 newMax) external onlyGov {
        require(newMax >= 10, "Minimum 10 holders");
        require(newMax <= 500, "Maximum 500 holders");
        maxTopHolders = newMax;
        emit MaxTopHoldersUpdated(newMax);
    }

    /**
* @notice Sets the vault address where remaining tokens are sent.
* @param _vault The new vault address.
     */
    function setVaultAddress(address _vault) external onlyGov {
        require(_vault != address(0), "Invalid vault address");
        vaultAddress = _vault;
        emit VaultUpdated(_vault);
    }

    /**
     * @notice Returns the complete list of top holders for the frontend
     * @return Array with addresses of the top holders
     */
    function getTopHolders() external view returns (address[] memory) {
        return topHolders;
    }

    /**
     * @notice Returns detailed information about the top holders for the frontend
     * @return holders Array of addresses
     * @return balances Array of corresponding balances
     * @return eligibleStatus Array indicating if each holder is eligible
     */
    function getTopHoldersDetails() external view returns (
        address[] memory holders,
        uint256[] memory balances,
        bool[] memory eligibleStatus
    ) {
        uint256 length = topHolders.length;
        holders = new address[](length);
        balances = new uint256[](length);
        eligibleStatus = new bool[](length);
        
        for (uint256 i = 0; i < length; i++) {
            holders[i] = topHolders[i];
            balances[i] = hymToken.balanceOf(topHolders[i]);
            eligibleStatus[i] = isEligible(topHolders[i]);
        }
    }

    /**
     * @notice Returns statistics about known holders
     * @return totalHolders Total known holders
     * @return topHoldersCount NNumber of top holders
     * @return eligibleHolders NNumber of eligible holders
     */
    function getHolderStats() external view returns (
        uint256 totalHolders,
        uint256 topHoldersCount,
        uint256 eligibleHolders
    ) {
        totalHolders = allHolders.length;
        topHoldersCount = topHolders.length;
        
        for (uint256 i = 0; i < allHolders.length; i++) {
            if (isEligible(allHolders[i])) {
                eligibleHolders++;
            }
        }
    }

    /**
     * @notice Returns information about the upcoming automatic updates
     * @return canUpdateTopHolders If top holders can be updated now
     * @return timeUntilTopHoldersUpdate Time until next top holders update
     * @return canDistribute If distribution can be done now
     * @return timeUntilDistribution Time until next distribution
     */
    function getAutomationInfo() external view returns (
        bool canUpdateTopHolders,
        uint256 timeUntilTopHoldersUpdate,
        bool canDistribute,
        uint256 timeUntilDistribution
    ) {
        uint256 nextTopHoldersUpdate = lastTopHoldersUpdate + topHoldersUpdateInterval;
        uint256 nextDistribution = lastDistribution + distributionInterval;
        
        if (block.timestamp >= nextTopHoldersUpdate) {
            canUpdateTopHolders = autoTopHoldersUpdateEnabled;
            timeUntilTopHoldersUpdate = 0;
        } else {
            canUpdateTopHolders = false;
            timeUntilTopHoldersUpdate = nextTopHoldersUpdate - block.timestamp;
        }
        
        if (block.timestamp >= nextDistribution) {
            canDistribute = autoDistributionEnabled && hymToken.balanceOf(address(this)) > 0;
            timeUntilDistribution = 0;
        } else {
            canDistribute = false;
            timeUntilDistribution = nextDistribution - block.timestamp;
        }
    }

    /**
* @notice Checks if the holder is eligible for distribution.
* @param holder The holder's address.
* @return True if the holder is eligible, false otherwise.
     */
    function isEligible(address holder) public view returns (bool) {
        return
            hymToken.balanceOf(holder) >= minHolding &&
            firstReceivedTimestamp[holder] != 0 &&
            block.timestamp >= firstReceivedTimestamp[holder] + holdingPeriod;
    }

    /**
     * @notice Estimates the proportional distribution for a specific holder
     * @param holder The holder's address
     * @return The estimated amount of tokens for distribution
     */
    function estimateDistribution(address holder) external view returns (uint256) {
        if (!isEligible(holder)) {
            return 0;
        }

        uint256 totalToDistribute = hymToken.balanceOf(address(this));
        if (totalToDistribute == 0) {
            return 0;
        }

        // Calculates total eligible balance of top holders
        uint256 totalEligibleBalance = 0;
        for (uint256 i = 0; i < topHolders.length; i++) {
            if (isEligible(topHolders[i])) {
                totalEligibleBalance += hymToken.balanceOf(topHolders[i]);
            }
        }

        if (totalEligibleBalance == 0) {
            return 0;
        }

        uint256 holderBalance = hymToken.balanceOf(holder);
        return (totalToDistribute * holderBalance) / totalEligibleBalance;
    }

    /**
     * @notice Distribution automation settings
     */
    function setAutoDistributionEnabled(bool enabled) external onlyGov {
        autoDistributionEnabled = enabled;
        emit AutoDistributionToggled(enabled);
    }

    function setDistributionInterval(uint256 intervalInSeconds) external onlyGov {
        require(intervalInSeconds >= 7 days, "Minimum interval: 7 days");
        require(intervalInSeconds <= 90 days, "Maximum interval: 90 days");
        distributionInterval = intervalInSeconds;
        emit DistributionIntervalUpdated(intervalInSeconds);
    }

    /**
     * @notice Updates the minimum amount required for a holder to be eligible.
     * @param amount New minimum value (in wei).
     */
    function setMinHolding(uint256 amount) external onlyGov {
        require(amount > 0, "Minimum holding must be greater than zero");
        minHolding = amount;
        emit MinHoldingUpdated(amount);
    }

    /**
     * @notice Updates the minimum holding period for eligibility.
     * @param duration New period in seconds.
     */
    function setHoldingPeriod(uint256 duration) external onlyGov {
        require(duration >= 1 days, "Holding period must be at least 1 day");
        require(duration <= 365 days, "Holding period too long");
        holdingPeriod = duration;
        emit HoldingPeriodUpdated(duration);
    }

    /**
     * @notice Returns the distribution history
     * @param limit Maximum number of records to return
     * @return Array with distribution history
     */
    function getDistributionHistory(uint256 limit) external view returns (DistributionRound[] memory) {
        uint256 length = distributionHistory.length;
        if (limit > length) limit = length;
        
        DistributionRound[] memory result = new DistributionRound[](limit);
        
        for (uint256 i = 0; i < limit; i++) {
            result[i] = distributionHistory[length - 1 - i]; // Most recent first
        }
        
        return result;
    }

    /**
     * @notice Allows the owner to withdraw all tokens from the contract in case of emergency.
     */
    function emergencyWithdrawAll() external onlyOwner nonReentrant {
        uint256 balance = hymToken.balanceOf(address(this));
        require(balance > 0, "Nothing to withdraw");
        require(vaultAddress != address(0), "Vault not set");
        require(hymToken.transfer(vaultAddress, balance), "Transfer failed");
        emit EmergencyWithdraw(vaultAddress, balance);
    }

    /**
     * @notice Emergency function to recover accidentally sent ERC20 tokens
     * @param token Address of the token to be recovered
     * @param amount Amount to be recovered
     */
    function emergencyRecoverToken(address token, uint256 amount) external onlyOwner {
        require(token != address(hymToken), "Cannot recover HYM");
        require(token != address(0), "Invalid token address");
        IERC20(token).transfer(owner(), amount);
    }

 

    function updateTopHolders() external {
        uint256 startGas = gasleft();
        lastUpdateGasUsed = startGas - gasleft();
    }
 
    function getGasInfo() external view returns (uint256 lastUpdateGas, uint256 estimatedDailyCost) {
        lastUpdateGas = lastUpdateGasUsed;
        estimatedDailyCost = lastUpdateGasUsed; // Update once per day
    }
}

"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "evmVersion": "paris",
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    }
  }
}}

Tags:
ERC20, Multisig, Swap, Multi-Signature, Factory|addr:0xcd2f563cd4a291234b090da9c8f63e8a323e7fa7|verified:true|block:23436032|tx:0x58f142ce8131791229ef78c8090f33d87c65641ddd69753d5e631760cebacdc7|first_check:1758788505

Submitted on: 2025-09-25 10:21:45

Comments

Log in to comment.

No comments yet.