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

LockToken

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

0 ETH

 

Транзакций

1

 

Компилятор

solc 0.8.22

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.22+commit.4fc1097e
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
shanghai
Лицензия
MIT
Совпадение
Частичноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
23 202 444
Транзакция создания
0x5f38df2855…cd0aa312b5

LockToken_UUPS_EDENA.sol

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

import "./Initializable.sol";
import "./UUPSUpgradeable.sol";
import "./OwnableUpgradeable.sol";
import "./PausableUpgradeable.sol";
import "./ReentrancyGuardUpgradeable.sol";
import "./ERC20Upgradeable.sol";

contract Approvable is Initializable, OwnableUpgradeable {
    address[] approveArr; // Manages contract or account addresses to control. Prevents illegal execution

    function __Approvable_init(address initialOwner) internal onlyInitializing {}

    // approve contract check - owner is automatically granted permission
    modifier onlyApproved() {
        bool approve = false;
        
        // owner is automatically granted approve permission
        if (owner() == msg.sender) {
            approve = true;
        } else {
            // check from approve array
            uint256 arrCnt = approveArr.length;
            for (uint256 i = 0; i < arrCnt; i++) {
                if (approveArr[i] == msg.sender) {
                    approve = true;
                    break;
                }
            }
        }
        
        require(approve, "Must call by Owner or Approved Contract");
        _;
    }

    function addApproveArr(address _approveAddress) public onlyOwner {
        require(_approveAddress != address(0), "Invalid address");
        require(!isApproved(_approveAddress), "Already approved");
        approveArr.push(_approveAddress);
    }

    function removeApproveArr(address _approveAddress) public onlyOwner {
        require(_approveAddress != address(0), "Invalid address");
        uint256 arrCnt = approveArr.length;
        bool found = false;
        for (uint256 i = 0; i < arrCnt; i++) {
            if (approveArr[i] == _approveAddress) {
                // move last element to current position
                approveArr[i] = approveArr[arrCnt - 1];
                // decrease array length
                approveArr.pop();
                found = true;
                break;
            }
        }
    }

    function isApproved(address checkAddress) public view returns (bool) {
        require(checkAddress != address(0), "checkAddress is null");

        // owner is automatically granted approve permission
        if (owner() == checkAddress) {
            return true;
        }

        // check from approve array
        bool approve = false;
        uint256 arrCnt = approveArr.length;
        for (uint256 i = 0; i < arrCnt; i++) {
            if (approveArr[i] == checkAddress) {
                approve = true;
                break;
            }
        }
        return approve;
    }

    function getApprovedList() public view returns (address[] memory) {
        return approveArr;
    }
}

contract LockToken is
    Initializable,
    ERC20Upgradeable,
    PausableUpgradeable,
    OwnableUpgradeable,
    UUPSUpgradeable,
    ReentrancyGuardUpgradeable,
    Approvable {
    uint256 public lockupDays; // Default lockup period 3 months calculated as 90 days
    
    // Auto unlock feature activation status
    bool public autoUnlockEnabled;
    
    struct LockInfo {
        uint256 _releaseTime;
        uint256 _amount;
    }

    mapping(address => LockInfo[]) public timelockList;
    mapping(address => bool) public frozenAccount;

    // Mapping for managing locked token amounts
    mapping(address => uint256) public lockedAmount;

    // Snapshot related variables - EXACT original layout
    mapping(uint256 => uint256) public snapshotTotalSupply;
    mapping(uint256 => uint256) public snapshotTimestamp;
    mapping(uint256 => mapping(address => uint256)) public snapshotBalances;
    uint256 public currentSnapshotId;

    // Address management - EXACT original layout
    address[] public addressList;
    mapping(address => bool) public isAddressRegistered;
    mapping(uint256 => address[]) public snapshotAddresses;

    // Lock constraints and security - These were missing from variable declarations
    uint256 public constant MAX_LOCKS_PER_ADDRESS = 100;
    uint256 public constant MAX_LOCK_DURATION = 1460 days; // 4 years maximum
    mapping(address => uint256) public lastLockTime;
    uint256 public lockCooldownPeriod;
    mapping(uint256 => bool) public snapshotFinalized;

    // NEW VARIABLES - Added after all existing inherited variables for upgrade compatibility
    uint256[] private _allSnapshotIds;
    mapping(uint256 => bool) public snapshotCompleted;
    mapping(uint256 => uint256) public snapshotProcessedIndex;
    mapping(uint256 => bool) public snapshotProcessing;
    uint256 public defaultBatchSize;

    // Storage gap - reserved space for future upgrades  
    uint256[42] private __gap;

    // Events
    event Lock(address indexed holder, uint256 value, uint256 releaseTime, address indexed operator);
    event Unlock(address indexed holder, uint256 value, address indexed operator);
    event Freeze(address indexed holder);
    event Unfreeze(address indexed holder);
    event SnapshotCreated(uint256 indexed snapshotId, uint256 totalAddresses, uint256 totalSupply);
    
    // Administrative events
    event AddressRegistered(address indexed registrar, address indexed newAddress);
    event AddressUnregistered(address indexed registrar, address indexed removedAddress);
    event LockupDaysChanged(address indexed owner, uint256 oldDays, uint256 newDays);
    event AutoUnlockEnabledChanged(address indexed owner, bool enabled);
    event LockCooldownChanged(address indexed owner, uint256 oldCooldown, uint256 newCooldown);
    event SnapshotFinalized(uint256 indexed snapshotId);
    event SnapshotCompleted(uint256 indexed snapshotId, uint256 totalAddresses);
    event SnapshotProcessingStarted(uint256 indexed snapshotId);
    event SnapshotProcessingResumed(uint256 indexed snapshotId);

    modifier notFrozen(address _holder) {
        require(!frozenAccount[_holder]);
        _;
    }

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    function initialize(
        string memory tokenName,
        string memory tokenSymbol,
        uint256 totalSupplyEth,
        address initialOwner
    ) public initializer {
        __ERC20_init(tokenName, tokenSymbol);
        __Pausable_init();
        __Ownable_init();
        __UUPSUpgradeable_init();
        __ReentrancyGuard_init();
        __Approvable_init(initialOwner);
        
        transferOwnership(initialOwner);
        
        lockupDays = 90; // Default 90 days
        autoUnlockEnabled = true; // Default enabled
        defaultBatchSize = 100; // Default batch size
        lockCooldownPeriod = 1 hours; // Default cooldown period
        
        uint256 totalSupplyWei = totalSupplyEth * (10**18);
        _mint(initialOwner, totalSupplyWei);
        
        // Register initial owner to addressList
        addressList.push(initialOwner);
        isAddressRegistered[initialOwner] = true;
    }

    function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}

    // Utility functions
    function _addDays(uint256 _days) internal view returns (uint256) {
        require(_days <= 3650, "Days cannot exceed 10 years");
        return (block.timestamp + (_days * 24 * 60 * 60));
    }

    function _ethToWei(uint256 _ethVal) internal pure returns (uint256) {
        return (_ethVal * (10**18));
    }

    // Internal functions
    function _lock(address holder, uint256 value, uint256 releaseTime) internal {
        require(holder != address(0), "Cannot lock zero address");
        require(value > 0, "Lock amount must be greater than 0");
        require(releaseTime > block.timestamp, "Release time must be in the future");
        require(releaseTime <= block.timestamp + MAX_LOCK_DURATION, "Lock duration exceeds maximum");
        require(balanceOf(holder) - lockedAmount[holder] >= value, "Insufficient unlocked balance for lock");
        require(timelockList[holder].length < MAX_LOCKS_PER_ADDRESS, "Too many active locks");
        
        // Anti-frontrunning cooldown check (only for third-party locks)
        uint256 cooldown = lockCooldownPeriod > 0 ? lockCooldownPeriod : 1 hours;
        if (msg.sender != holder && lastLockTime[holder] + cooldown > block.timestamp) {
            require(lastLockTime[holder] + cooldown <= block.timestamp, "Lock cooldown period not passed");
        }

        lockedAmount[holder] += value;
        timelockList[holder].push(LockInfo(releaseTime, value));
        lastLockTime[holder] = block.timestamp;
        
        // Sort the locks by release time to maintain order
        _sortLocksByReleaseTime(holder);
        
        emit Lock(holder, value, releaseTime, msg.sender);
    }
    
    // Sort locks by release time for efficient processing
    function _sortLocksByReleaseTime(address holder) internal {
        LockInfo[] storage locks = timelockList[holder];
        uint256 length = locks.length;
        
        // Simple insertion sort for small arrays (efficient for MAX_LOCKS_PER_ADDRESS = 100)
        for (uint256 i = 1; i < length; i++) {
            LockInfo memory key = locks[i];
            uint256 j = i;
            while (j > 0 && locks[j - 1]._releaseTime > key._releaseTime) {
                locks[j] = locks[j - 1];
                j--;
            }
            locks[j] = key;
        }
    }

    // Common unlock logic
    function _removeLock(address holder, uint256 idx) internal {
        LockInfo storage lockInfo = timelockList[holder][idx];
        uint256 amount = lockInfo._amount;
        // Remove lock information (move last element to current position)
        uint256 lastIndex = timelockList[holder].length - 1;
        if (idx != lastIndex) {
            timelockList[holder][idx] = timelockList[holder][lastIndex];
        }
        timelockList[holder].pop();
        // Decrease locked amount
        require(lockedAmount[holder] >= amount, "Locked amount underflow");
        lockedAmount[holder] -= amount;
        emit Unlock(holder, amount, msg.sender);
    }

    function _unlock(address holder, uint256 idx) internal {
        require(holder != address(0), "Cannot unlock zero address");
        require(timelockList[holder].length > idx, "Lock index does not exist");
        require(block.timestamp >= timelockList[holder][idx]._releaseTime, "Lock period not expired");
        _removeLock(holder, idx);
    }

    // Unlock all expired locks and return the number of unlocked locks
    // Optimized to stop at first non-expired lock since locks are sorted
    function _autoUnlock(address holder) internal returns (uint256) {
        require(holder != address(0), "Cannot unlock zero address");
        uint256 unlockedCount = 0;
        
        // Since locks are sorted by release time, we can process from beginning
        // and stop when we hit the first non-expired lock
        while (timelockList[holder].length > 0 && 
               block.timestamp >= timelockList[holder][0]._releaseTime) {
            _removeLock(holder, 0);
            unlockedCount++;
        }
        
        return unlockedCount;
    }

    // Override hook to allow transfer only for unlocked tokens in transfer/transferFrom
    function _beforeTokenTransfer(address from, address to, uint256 amount)
        internal
        override(ERC20Upgradeable)
        whenNotPaused
    {
        super._beforeTokenTransfer(from, to, amount); 

        if (from != address(0)) {
            require(
                balanceOf(from) - lockedAmount[from] >= amount,
                "Transfer amount exceeds unlocked balance"
            );
        }
    }

    // Configuration functions
    function setLockupDays(uint256 _lockupDays) public onlyOwner {
        require(_lockupDays > 0 && _lockupDays <= 3650, "Lockup days must be between 1 and 3650");
        uint256 oldDays = lockupDays;
        lockupDays = _lockupDays;
        emit LockupDaysChanged(msg.sender, oldDays, _lockupDays);
    }

    function setAutoUnlockEnabled(bool _enabled) public onlyOwner {
        autoUnlockEnabled = _enabled;
        emit AutoUnlockEnabledChanged(msg.sender, _enabled);
    }

    function setLockCooldownPeriod(uint256 _cooldownPeriod) public onlyOwner {
        require(_cooldownPeriod <= 24 hours, "Cooldown period too long");
        uint256 oldCooldown = lockCooldownPeriod;
        lockCooldownPeriod = _cooldownPeriod;
        emit LockCooldownChanged(msg.sender, oldCooldown, _cooldownPeriod);
    }

    // Address management functions
    function registerAddress(address _address) public onlyOwner {
        require(_address != address(0), "Cannot register zero address");
        require(!isAddressRegistered[_address], "Address already registered");
        
        addressList.push(_address);
        isAddressRegistered[_address] = true;
        emit AddressRegistered(msg.sender, _address);
    }

    function unregisterAddress(address _address) public onlyOwner {
        require(_address != address(0), "Cannot unregister zero address");
        require(isAddressRegistered[_address], "Address not registered");
        
        // Remove from addressList
        uint256 length = addressList.length;
        bool found = false;
        for (uint256 i = 0; i < length; i++) {
            if (addressList[i] == _address) {
                // move last element to current position
                addressList[i] = addressList[length - 1];
                addressList.pop();
                found = true;
                break;
            }
        }
        
        if (found) {
            isAddressRegistered[_address] = false;
            emit AddressUnregistered(msg.sender, _address);
        }
    }

    function getRegisteredAddresses() public view returns (address[] memory) {
        return addressList;
    }

    function getRegisteredAddressCount() public view returns (uint256) {
        return addressList.length;
    }

    // Lock related query functions
    function getLockCount(address holder) public view returns (uint256) {
        return timelockList[holder].length;
    }

    // Clear lock accounting functions
    function getLockedIncludingExpired(address owner) public view returns (uint256) {
        return lockedAmount[owner];
    }

    function getLockedUnexpired(address holder) public view returns (uint256) {
        uint256 lockTotal = 0;
        
        // Since locks are sorted by release time, we can break early
        for (uint256 idx = 0; idx < timelockList[holder].length; idx++) {
            if (timelockList[holder][idx]._releaseTime > block.timestamp) {
                lockTotal += timelockList[holder][idx]._amount;
            } else {
                // All subsequent locks will also be expired, so we can continue
                // to count them but we know they don't contribute to current locked amount
                continue;
            }
        }
        return lockTotal;
    }

    // Legacy functions for backward compatibility
    function getLockedBalance(address owner) public view returns (uint256) {
        return getLockedIncludingExpired(owner);
    }

    function getLockTotal(address holder) public view returns (uint256) {
        return getLockedUnexpired(holder);
    }

    // Returns the available (transferable) balance: total balance minus locked amount
    function getAvailableBalance(address owner) public view returns (uint256) {
        uint256 balance = balanceOf(owner);
        uint256 locked = lockedAmount[owner];
        if (balance > locked) {
            return balance - locked;
        } else {
            return 0;
        }
    }

    // Overall lock status summary query
    function getLockSummary() public view returns (
        uint256 totalLockedAddresses,
        uint256 totalLockedAmount,
        uint256 totalLockCount
    ) {
        address[] memory addresses = getRegisteredAddresses();
        uint256 totalAddresses = 0;
        uint256 totalAmount = 0;
        uint256 totalCount = 0;
        
        for (uint256 i = 0; i < addresses.length; i++) {
            uint256 lockedBalance = getLockedBalance(addresses[i]);
            if (lockedBalance > 0) {
                totalAddresses++;
                totalAmount += lockedBalance;
                totalCount += getLockCount(addresses[i]);
            }
        }
        
        return (totalAddresses, totalAmount, totalCount);
    }

    // Overall lock status detailed query
    function getAllLockedBalances() public view returns (
        address[] memory holders,
        uint256[] memory lockedAmounts,
        uint256[] memory lockCounts
    ) {
        address[] memory addresses = getRegisteredAddresses();
        uint256 lockedCount = 0;
        
        // Calculate number of locked addresses
        for (uint256 i = 0; i < addresses.length; i++) {
            if (getLockedBalance(addresses[i]) > 0) {
                lockedCount++;
            }
        }
        
        // Initialize result arrays
        holders = new address[](lockedCount);
        lockedAmounts = new uint256[](lockedCount);
        lockCounts = new uint256[](lockedCount);
        
        uint256 index = 0;
        for (uint256 i = 0; i < addresses.length; i++) {
            uint256 lockedBalance = getLockedBalance(addresses[i]);
            if (lockedBalance > 0) {
                holders[index] = addresses[i];
                lockedAmounts[index] = lockedBalance;
                lockCounts[index] = getLockCount(addresses[i]);
                index++;
            }
        }
        
        return (holders, lockedAmounts, lockCounts);
    }

    // Detailed lock information query for specific address
    function getLockDetails(address holder) public view returns (
        uint256 lockCount,
        uint256 totalLockedAmount,
        uint256[] memory releaseTimes,
        uint256[] memory amounts
    ) {
        lockCount = getLockCount(holder);
        totalLockedAmount = getLockedBalance(holder);
        
        releaseTimes = new uint256[](lockCount);
        amounts = new uint256[](lockCount);
        
        for (uint256 i = 0; i < lockCount; i++) {
            LockInfo storage lockInfo = timelockList[holder][i];
            releaseTimes[i] = lockInfo._releaseTime;
            amounts[i] = lockInfo._amount;
        }
        
        return (lockCount, totalLockedAmount, releaseTimes, amounts);
    }

    function transferWithLock(
        address holder,
        uint256 value,
        uint256 releaseTime
    ) public onlyApproved nonReentrant returns (bool) {
        require(holder != address(0), "Cannot transfer to zero address");
        require(value > 0, "Transfer amount must be greater than 0");
        require(balanceOf(msg.sender) - lockedAmount[msg.sender] >= value, "Insufficient unlocked balance");
        
        // Auto register if recipient is not registered
        if (!isAddressRegistered[holder]) {
            addressList.push(holder);
            isAddressRegistered[holder] = true;
        }
        
        // Transfer tokens to holder first
        _transfer(msg.sender, holder, value);
        // Then lock the transferred tokens
        _lock(holder, value, releaseTime);
        return true;
    }

    function transferWithLockEasy(
        address holder,
        uint256 valueEth,
        uint256 lockupDaysParam
    ) public onlyApproved returns (bool) {
        uint256 valueWei = valueEth * (10**18);
        uint256 releaseTime = block.timestamp + (lockupDaysParam * 1 days);
        return transferWithLock(holder, valueWei, releaseTime);
    }

    function transferWithLockBase(
        address holder,
        uint256 value
    ) public onlyApproved returns (bool) {
        uint256 releaseTime = block.timestamp + (lockupDays * 1 days);
        return transferWithLock(holder, value, releaseTime);
    }

    // Unlock related functions
    function unlock(address holder, uint256 idx) public onlyApproved nonReentrant returns (bool) {
        require(holder != address(0), "Cannot unlock zero address");
        require(timelockList[holder].length > idx, "There is not lock info.");
        _unlock(holder, idx);
        return true;
    }

    function claim() public nonReentrant returns (uint256) {
        address holder = msg.sender;
        return _autoUnlock(holder);
    }

    // Function for approved users to unlock others' locks
    function manualUnlock(address holder) public onlyApproved nonReentrant returns (uint256) {
        require(holder != address(0), "Cannot unlock zero address");
        return _autoUnlock(holder);
    }

    // Token transfer functions
    function transfer(address to, uint256 value)
        public
        override
        whenNotPaused
        notFrozen(msg.sender)
        notFrozen(to)  
        nonReentrant
        returns (bool)
    {
        require(to != address(0), "Cannot transfer to zero address");
        require(value > 0, "Transfer amount must be greater than 0");
        if (autoUnlockEnabled && timelockList[msg.sender].length > 0) {
            _autoUnlock(msg.sender);
        }
        _registerAddressIfNeeded(to);
        return super.transfer(to, value);
    }

    function transferFrom(
        address from,
        address to,
        uint256 value
    ) public override whenNotPaused notFrozen(from) notFrozen(to) nonReentrant returns (bool) {
        require(from != address(0), "Cannot transfer from zero address");
        require(to != address(0), "Cannot transfer to zero address");
        require(value > 0, "Transfer amount must be greater than 0");
        if (autoUnlockEnabled && timelockList[from].length > 0) {
            _autoUnlock(from);
        }
        _registerAddressIfNeeded(to);
        return super.transferFrom(from, to, value);
    }

    // Snapshot related functions - Batch processing implementation with auto-start
    function createSnapshot() public onlyOwner returns (uint256) {
        uint256 snapshotId = currentSnapshotId + 1;
        currentSnapshotId = snapshotId;
        
        _allSnapshotIds.push(snapshotId);
        snapshotTotalSupply[snapshotId] = totalSupply();
        snapshotTimestamp[snapshotId] = block.timestamp;
        snapshotFinalized[snapshotId] = false;
        
        // Initialize batch processing state
        snapshotCompleted[snapshotId] = false;
        snapshotProcessedIndex[snapshotId] = 0;
        snapshotProcessing[snapshotId] = true;
        
        // Pause all token transfers during snapshot processing (only if not already paused)
        if (!paused()) {
            _pause();
        }
        
        emit SnapshotCreated(snapshotId, 0, totalSupply());
        emit SnapshotProcessingStarted(snapshotId);
        
        // Automatically start processing with default batch size
        uint256 batchSize = defaultBatchSize > 0 ? defaultBatchSize : 100;
        bool completed = _processSnapshotInternal(snapshotId, batchSize);
        
        if (completed) {
            // Small holder set - completed in one transaction
            emit SnapshotCompleted(snapshotId, addressList.length);
        }
        
        return snapshotId;
    }
    
    // Process snapshot in batches to avoid gas limit issues
    function processSnapshot(uint256 snapshotId, uint256 batchSize) public onlyOwner returns (bool completed) {
        require(snapshotId > 0 && snapshotId <= currentSnapshotId, "Invalid snapshot ID");
        require(!snapshotCompleted[snapshotId], "Snapshot already completed");
        require(snapshotProcessing[snapshotId], "Snapshot not in processing state");
        require(batchSize > 0 && batchSize <= 200, "Invalid batch size"); // Limit batch size for safety
        
        return _processSnapshotInternal(snapshotId, batchSize);
    }
    
    // Internal function for snapshot processing logic
    function _processSnapshotInternal(uint256 snapshotId, uint256 batchSize) internal returns (bool completed) {
        uint256 startIndex = snapshotProcessedIndex[snapshotId];
        uint256 endIndex = startIndex + batchSize;
        
        if (endIndex > addressList.length) {
            endIndex = addressList.length;
        }
        
        // Process batch of addresses
        for (uint256 i = startIndex; i < endIndex; i++) {
            address account = addressList[i];
            uint256 balance = balanceOf(account);
            
            if (balance > 0) {
                // Only add if not already recorded for this snapshot
                if (snapshotBalances[snapshotId][account] == 0) {
                    snapshotAddresses[snapshotId].push(account);
                }
                snapshotBalances[snapshotId][account] = balance;
            }
        }
        
        // Update processed index
        snapshotProcessedIndex[snapshotId] = endIndex;
        
        // Check if processing is complete
        if (endIndex >= addressList.length) {
            snapshotCompleted[snapshotId] = true;
            snapshotProcessing[snapshotId] = false;
            
            // Resume token transfers (only if we were the ones who paused it)
            if (paused()) {
                _unpause();
            }
            
            return true;
        }
        
        return false;
    }
    
    // Finalize snapshot to prevent further modifications
    function finalizeSnapshot(uint256 snapshotId) public onlyOwner {
        require(snapshotId > 0 && snapshotId <= currentSnapshotId, "Invalid snapshot ID");
        require(!snapshotFinalized[snapshotId], "Snapshot already finalized");
        require(snapshotCompleted[snapshotId], "Snapshot must be completed before finalization");
        
        snapshotFinalized[snapshotId] = true;
        emit SnapshotFinalized(snapshotId);
    }
 

    // Query address balance at specific snapshot (including locked quantity)
    function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
        require(snapshotId > 0 && snapshotId <= currentSnapshotId, "Invalid snapshot ID");
        require(snapshotCompleted[snapshotId], "Snapshot not completed yet");
        
        // Direct access - all completed snapshots have complete data
        return snapshotBalances[snapshotId][account];
    }

    function getSnapshotTotalSupply(uint256 snapshotId) public view returns (uint256) {
        return snapshotTotalSupply[snapshotId];
    }

    function getSnapshotTimestamp(uint256 snapshotId) public view returns (uint256) {
        return snapshotTimestamp[snapshotId];
    }

    function getAllSnapshotIds() public view returns (uint256[] memory) {
        return _allSnapshotIds;
    }

    function getAccountSnapshotIds(address account) public view returns (uint256[] memory) {
        // In batch system, find all snapshots where this account has balance
        uint256[] memory allSnapshots = _allSnapshotIds;
        uint256 count = 0;
        
        // Count snapshots with balance
        for (uint256 i = 0; i < allSnapshots.length; i++) {
            if (snapshotBalances[allSnapshots[i]][account] > 0) {
                count++;
            }
        }
        
        // Create result array
        uint256[] memory result = new uint256[](count);
        uint256 index = 0;
        for (uint256 i = 0; i < allSnapshots.length; i++) {
            if (snapshotBalances[allSnapshots[i]][account] > 0) {
                result[index] = allSnapshots[i];
                index++;
            }
        }
        
        return result;
    }
    
    // Snapshot status and progress query functions
    function getSnapshotStatus(uint256 snapshotId) external view returns (
        bool completed,
        uint256 processedCount,
        uint256 totalCount,
        uint256 progressPercentage,
        bool isProcessing,
        bool isFinalized
    ) {
        require(snapshotId > 0 && snapshotId <= currentSnapshotId, "Invalid snapshot ID");
        
        completed = snapshotCompleted[snapshotId];
        processedCount = snapshotProcessedIndex[snapshotId];
        totalCount = addressList.length;
        progressPercentage = totalCount > 0 ? (processedCount * 100) / totalCount : 100;
        isProcessing = snapshotProcessing[snapshotId];
        isFinalized = snapshotFinalized[snapshotId];
    }
    
    function isSnapshotCompleted(uint256 snapshotId) external view returns (bool) {
        return snapshotCompleted[snapshotId];
    }
    
    function isSnapshotProcessing(uint256 snapshotId) external view returns (bool) {
        return snapshotProcessing[snapshotId];
    }
    
    function getSnapshotProgress(uint256 snapshotId) external view returns (
        uint256 processedAddresses,
        uint256 totalAddresses,
        uint256 remainingAddresses
    ) {
        require(snapshotId > 0 && snapshotId <= currentSnapshotId, "Invalid snapshot ID");
        
        processedAddresses = snapshotProcessedIndex[snapshotId];
        totalAddresses = addressList.length;
        remainingAddresses = totalAddresses > processedAddresses ? 
            totalAddresses - processedAddresses : 0;
    }
    
    // Emergency function to resume processing if needed
    function resumeSnapshotProcessing(uint256 snapshotId) external onlyOwner {
        require(snapshotId > 0 && snapshotId <= currentSnapshotId, "Invalid snapshot ID");
        require(!snapshotCompleted[snapshotId], "Snapshot already completed");
        require(!snapshotProcessing[snapshotId], "Snapshot already processing");
        
        snapshotProcessing[snapshotId] = true;
        if (!paused()) {
            _pause();
        }
        
        emit SnapshotProcessingResumed(snapshotId);
    }
    
    // Emergency function to cancel snapshot processing and unpause
    function cancelSnapshotProcessing(uint256 snapshotId) external onlyOwner {
        require(snapshotId > 0 && snapshotId <= currentSnapshotId, "Invalid snapshot ID");
        require(snapshotProcessing[snapshotId], "Snapshot not processing");
        require(!snapshotCompleted[snapshotId], "Cannot cancel completed snapshot");
        
        snapshotProcessing[snapshotId] = false;
        if (paused()) {
            _unpause();
        }
        
        // Note: This doesn't reset processed data, just stops processing
        // Owner can resume later if needed
    }
    
    // Function to set default batch size
    function setDefaultBatchSize(uint256 _batchSize) external onlyOwner {
        require(_batchSize > 0 && _batchSize <= 200, "Invalid batch size");
        defaultBatchSize = _batchSize;
    }
    
    // Convenience function to continue processing with default batch size
    function continueSnapshot(uint256 snapshotId) external onlyOwner returns (bool completed) {
        uint256 batchSize = defaultBatchSize > 0 ? defaultBatchSize : 100;
        return processSnapshot(snapshotId, batchSize);
    }
    
    // Emergency function to completely reset snapshot processing
    function resetSnapshotProcessing(uint256 snapshotId) external onlyOwner {
        require(snapshotId > 0 && snapshotId <= currentSnapshotId, "Invalid snapshot ID");
        require(snapshotProcessing[snapshotId] || !snapshotCompleted[snapshotId], "Cannot reset completed snapshot");
        
        // Reset processing state
        snapshotProcessing[snapshotId] = false;
        snapshotProcessedIndex[snapshotId] = 0;
        snapshotCompleted[snapshotId] = false;
        
        // Clear any partial snapshot data (expensive operation)
        address[] memory snapshotAddrs = snapshotAddresses[snapshotId];
        for (uint256 i = 0; i < snapshotAddrs.length; i++) {
            delete snapshotBalances[snapshotId][snapshotAddrs[i]];
        }
        
        // Clear the address list for this snapshot
        delete snapshotAddresses[snapshotId];
        
        // Unpause if we were paused
        if (paused()) {
            _unpause();
        }
    }

    // Pause management functions
    function pause() public onlyOwner {
        _pause();
    }

    function unpause() public onlyOwner {
        _unpause();
    }

    // Account management functions
    function freezeAccount(address holder) public onlyOwner {
        require(holder != address(0), "Cannot freeze zero address");
        frozenAccount[holder] = true;
        emit Freeze(holder);
    }

    function unfreezeAccount(address holder) public onlyOwner {
        require(holder != address(0), "Cannot unfreeze zero address");
        frozenAccount[holder] = false;
        emit Unfreeze(holder);
    }

    // Token management functions
    // function mint(address to, uint256 amount) public onlyOwner returns (bool) {
    //     require(to != address(0), "Cannot mint to zero address");
    //     require(amount > 0, "Mint amount must be greater than 0");
    //     _mint(to, amount);
    //     return true;
    // }

    function burn(uint256 amount) public returns (bool) {
        require(amount > 0, "Burn amount must be greater than 0");
        require(balanceOf(msg.sender) - lockedAmount[msg.sender] >= amount, "Insufficient unlocked balance for burn");
        _burn(msg.sender, amount);
        return true;
    }

    // Address registration internal function
    function _registerAddressIfNeeded(address _address) internal {
        if (_address != address(0) && !isAddressRegistered[_address]) {
            addressList.push(_address);
            isAddressRegistered[_address] = true;
        }
    }
} 

Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                revert(add(returndata, 0x20), mload(returndata))
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

AddressUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)

pragma solidity 0.8.22;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

ContextUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity 0.8.22;
import "./Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.21;

import {IBeacon} from "./IBeacon.sol";
import {IERC1967} from "./IERC1967.sol";
import {Address} from "./Address.sol";
import {StorageSlot} from "./StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

ERC20Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)

pragma solidity 0.8.22;

import "./IERC20Upgradeable.sol";
import "./IERC20MetadataUpgradeable.sol";
import "./ContextUpgradeable.sol";
import "./Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[45] private __gap;
}

Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)

pragma solidity >=0.4.16;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

IERC1967.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)

pragma solidity >=0.4.11;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

IERC20MetadataUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity 0.8.22;

import "./IERC20Upgradeable.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

IERC20Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity 0.8.22;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20Upgradeable {
    /**
     * @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);
}

Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)

pragma solidity 0.8.22;

import "./AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original
     * initialization step. This is essential to configure modules that are added through upgrades and that require
     * initialization.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized < type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }
}

OwnableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity 0.8.22;

import "./ContextUpgradeable.sol";
import "./Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    function __Ownable_init() internal onlyInitializing {
        __Ownable_init_unchained();
    }

    function __Ownable_init_unchained() internal onlyInitializing {
        _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 anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing 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);
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

PausableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity 0.8.22;

import "./ContextUpgradeable.sol";
import "./Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @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);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _paused = false;
    }

    /**
     * @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 {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @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());
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

ReentrancyGuardUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity 0.8.22;
import "./Initializable.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 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 ReentrancyGuardUpgradeable is Initializable {
    // 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;

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _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() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

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
        }
    }
}

UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "./draft-IERC1822.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

draft-IERC1822.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)

pragma solidity >=0.4.16;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

draft-IERC1822Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)

pragma solidity 0.8.22;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822ProxiableUpgradeable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}
Настройки компилятораПоказать
{
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "shanghai"
}

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

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