PEPETUAL

Description:

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

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "contracts/pepetual.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

interface IUniswapV2Factory {
    function createPair(address tokenA, address tokenB) external returns (address pair);
    function getPair(address tokenA, address tokenB) external view returns (address pair);
}

interface IUniswapV2Router02 {
    function factory() external view returns (address);
    function WETH() external view returns (address);
    function addLiquidityETH(
        address token,
        uint256 amountTokenDesired,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
    function getAmountsOut(uint256 amountIn, address[] calldata path)
        external
        view
        returns (uint256[] memory amounts);
    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;
}

interface IPondManager {
    function addToPond(uint256 pepeAmount) external;
    function updateHolderEligibility(address holder, uint256 newBalance) external;
    function paused() external view returns (bool);
}

contract PEPETUAL is ERC20, ReentrancyGuard, Pausable, Ownable {
    using SafeERC20 for IERC20;

    // ==================== Token Configuration ====================

    uint256 public constant MAX_TAX_RATE = 1000; // 10% maximum
    uint256 public taxRate = 969; // 9.69% default
    uint256 private constant TAX_DIVISOR = 10000;

    // Fee distribution (matching original FeeHandlerV5_PEPE)
    uint256 public constant POND_BPS = 6900; // 6.9% → Pond
    uint256 public constant PEPE_BURN_BPS = 690; // 0.69% → PEPE burn
    uint256 public constant SELF_BURN_BPS = 690; // 0.69% → PEPETUAL burn
    uint256 public constant REWARDS_BPS = 690; // 0.69% → Holder rewards
    uint256 public constant DEV_BPS = 690; // 0.69% → Dev
    uint256 public constant ART_BPS = 30; // 0.03% → Art
    uint256 public constant TOTAL_BPS = 9690; // Total must equal 9690

    // ==================== Router and Trading ====================

    IUniswapV2Router02 public immutable uniswapV2Router;
    address public immutable uniswapV2Pair;
    IERC20 public PEPE;
    address public immutable WETH;

    mapping(address => bool) public excludedFromFees;
    mapping(address => bool) public automatedMarketMakerPairs;
    mapping(address => bool) public isLimitExempt;

    // Transfer restrictions
    bool public walletToWalletTransfersDisabled = false; // Can be toggled by owner

    // Limits
    uint256 public maxTxAmount;
    uint256 public maxWalletAmount;
    bool public limitsInEffect = true;

    // ==================== MEV Protection (Minimal) ====================

    // Only keep basic sandwich protection
    mapping(address => uint256) public lastBuyBlock;
    uint256 public sandwichProtectionBlocks = 1; // Wait 1 block after buying before selling
    bool public mevProtectionEnabled = true;

    // ==================== Whale Protection ====================

    struct WhaleConfig {
        uint256 whaleThreshold; // Balance threshold for whale status
        uint256 maxSellPercent; // Max % of balance whale can sell
        uint256 sellCooldown; // Cooldown between whale sells (blocks)
        uint256 progressiveTaxRate; // Additional tax for whales
    }

    WhaleConfig public whaleConfig = WhaleConfig({
        whaleThreshold: 10000 * 10 ** 18, // 10k tokens = whale
        maxSellPercent: 500, // 5% max sell
        sellCooldown: 50, // ~10 minute cooldown
        progressiveTaxRate: 200 // +2% tax for whales
     });

    mapping(address => uint256) public lastWhaleSell;
    mapping(address => bool) public isWhaleExempt;

    // ==================== Rewards System ====================

    struct RewardSnapshot {
        uint256 totalSupplySnapshot;
        uint256 pepePerToken;
        uint256 timestamp;
    }

    RewardSnapshot[] public rewardSnapshots;
    mapping(address => bool) public excludedFromRewards;

    uint256 private constant REWARD_MAGNITUDE = 1e18;
    uint256 public magnifiedRewardsPerShare;
    mapping(address => int256) private magnifiedRewardCorrections;
    mapping(address => uint256) public withdrawnRewards;

    uint256 public reservedPepeForRewards; // PEPE reserved for rewards
    uint256 public totalPepeDistributed;
    uint256 public totalPepeClaimed;
    uint256 public minBalanceForRewards = 100 * 10 ** 18; // 100 tokens minimum
    uint256 public rewardClaimCooldown = 3600; // 1 hour
    mapping(address => uint256) public lastRewardClaim;

    uint256 public pendingRewardsBuffer;
    address[] private rewardExclusionList;
    mapping(address => bool) private rewardExclusionTracked;

    // ==================== Pond Integration ====================

    IPondManager public pondManager;

    // ==================== Reentrancy Protection ====================

    bool private processingFees;

    // ==================== Slippage Protection ====================

    uint256 public maxSlippageBPS = 100; // 1% default (100 basis points)

    // ==================== Fee Processing ====================

    uint256 public feeProcessingThreshold = 10000; // 0.001% of supply in basis points (10000 = 0.001%)

    // ==================== Wallets ====================

    address public devWallet;
    address public artWallet;

    uint256 public pendingPondPepe;

    // ==================== Events ====================

    event TaxRateUpdated(uint256 oldRate, uint256 newRate);
    event RewardSnapshotTaken(
        uint256 indexed snapshotId, uint256 indexed pepePerToken, uint256 totalSupply
    );
    event RewardsClaimed(address indexed user, uint256 indexed amount);
    event FeesProcessed(uint256 indexed rewards, uint256 indexed pond, uint256 indexed operations);
    event MEVProtectionTriggered(address indexed user, string reason);
    event WhaleProtectionTriggered(
        address indexed whale, uint256 indexed attemptedAmount, uint256 indexed allowedAmount
    );
    event ProgressiveTaxApplied(
        address indexed user, uint256 indexed baseTax, uint256 indexed finalTax
    );
    event PondManagerUpdated(address indexed oldManager, address indexed newManager);
    event RewardsExclusionUpdated(address indexed account, bool excluded);
    event ExternalPondPepeDeposited(address indexed sender, uint256 amount, uint256 forwarded);
    event ExternalRewardsPepeDeposited(address indexed sender, uint256 amount);
    event LimitExemptionUpdated(address indexed account, bool exempt);

    // ==================== Constructor ====================

    constructor(
        address router_,
        address pepe_,
        address devWallet_,
        address artWallet_,
        address pondManager_
    ) ERC20("PEPETUAL", "PEPETUAL") Ownable(msg.sender) {
        require(router_ != address(0), "Invalid router");
        require(pepe_ != address(0), "Invalid PEPE token");
        require(devWallet_ != address(0), "Invalid dev wallet");
        require(artWallet_ != address(0), "Invalid art wallet");
        // Allow temporary address for deployment
        // require(pondManager_ != address(0), "Invalid pond manager");

        uint256 totalSupply_ = 1_000_000_000 * 10 ** 18; // 1 billion tokens

        // Initialize router and pair
        uniswapV2Router = IUniswapV2Router02(router_);
        WETH = uniswapV2Router.WETH();
        PEPE = IERC20(pepe_);

        // Check if pair exists first
        address pairAddress =
            IUniswapV2Factory(uniswapV2Router.factory()).getPair(address(this), WETH);
        if (pairAddress == address(0)) {
            pairAddress =
                IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), WETH);
        }

        uniswapV2Pair = pairAddress;

        automatedMarketMakerPairs[uniswapV2Pair] = true;

        // Set wallets
        devWallet = devWallet_;
        artWallet = artWallet_;
        pondManager = IPondManager(pondManager_);

        // Set limits (2% of total supply)
        maxTxAmount = totalSupply_ * 200 / 10000;
        maxWalletAmount = totalSupply_ * 200 / 10000;

        // Exclude from fees and rewards
        excludedFromFees[owner()] = true;
        excludedFromFees[address(this)] = true;
        excludedFromFees[devWallet] = true;
        excludedFromFees[artWallet] = true;

        isLimitExempt[owner()] = true;
        isLimitExempt[address(this)] = true;

        excludedFromRewards[owner()] = true;
        excludedFromRewards[address(this)] = true;
        excludedFromRewards[uniswapV2Pair] = true;
        excludedFromRewards[address(0xdead)] = true;
        excludedFromRewards[devWallet] = true;
        excludedFromRewards[artWallet] = true;
        if (address(pondManager) != address(0)) {
            excludedFromRewards[address(pondManager)] = true;
        }

        _addRewardExclusion(owner());
        _addRewardExclusion(address(this));
        _addRewardExclusion(uniswapV2Pair);
        _addRewardExclusion(address(0xdead));
        _addRewardExclusion(devWallet);
        _addRewardExclusion(artWallet);
        if (address(pondManager) != address(0)) {
            _addRewardExclusion(address(pondManager));
        }

        // Approve router for swaps
        _approve(address(this), router_, type(uint256).max);

        // Mint tokens to owner
        _mint(owner(), totalSupply_);

        _syncRewardExclusion(owner(), true);
        _syncRewardExclusion(address(this), true);
        _syncRewardExclusion(uniswapV2Pair, true);
        _syncRewardExclusion(address(0xdead), true);
        _syncRewardExclusion(devWallet, true);
        _syncRewardExclusion(artWallet, true);
        if (address(pondManager) != address(0)) {
            _syncRewardExclusion(address(pondManager), true);
        }
    }

    // ==================== Core Transfer Logic ====================

    function _isTransferAllowed(address from, address to) internal view returns (bool) {
        // Always allow minting and burning
        if (from == address(0) || to == address(0)) return true;

        // Always allow transfers from/to this contract
        if (from == address(this) || to == address(this)) return true;

        // Always allow transfers from/to owner or limit-exempt addresses
        if (from == owner() || to == owner()) return true;
        if (isLimitExempt[from] || isLimitExempt[to]) return true;

        // Always allow transfers from/to excluded addresses
        if (excludedFromFees[from] || excludedFromFees[to]) return true;

        // Always allow transfers from/to DEX pairs and router
        if (automatedMarketMakerPairs[from] || automatedMarketMakerPairs[to]) return true;
        if (from == address(uniswapV2Router) || to == address(uniswapV2Router)) return true;

        // Check if wallet-to-wallet transfers are disabled
        if (walletToWalletTransfersDisabled) {
            return false; // Block wallet-to-wallet transfers
        }

        return true; // Allow if not disabled
    }

    function _update(address from, address to, uint256 amount) internal override {
        require(!paused(), "Token transfers paused");

        // Check if transfer is allowed (prevent wallet-to-wallet to force DEX usage)
        bool isAllowedTransfer = _isTransferAllowed(from, to);
        require(isAllowedTransfer, "Wallet-to-wallet transfers disabled");

        // Apply protections and limits
        if (mevProtectionEnabled && !excludedFromFees[from] && !excludedFromFees[to]) {
            _applyMEVProtection(from, to);
        }

        if (
            limitsInEffect && from != owner() && to != owner() && !excludedFromFees[from]
                && !excludedFromFees[to] && !isLimitExempt[from] && !isLimitExempt[to]
        ) {
            amount = _applyLimitsAndProtections(from, to, amount);
        }

        (uint256 netAmount, uint256 feeAmount, bool takeFeeFromRecipient) =
            _calculateTax(from, to, amount);

        if (feeAmount > 0 && !takeFeeFromRecipient) {
            _executeTokenTransfer(from, address(this), feeAmount);
        }

        _executeTokenTransfer(from, to, netAmount);

        if (feeAmount > 0 && takeFeeFromRecipient) {
            _executeTokenTransfer(to, address(this), feeAmount);
        }

        if (feeAmount > 0) {
            _processFeesIfNeeded();
        }

        if (address(pondManager) != address(0)) {
            if (from != address(0) && from != address(this)) {
                pondManager.updateHolderEligibility(from, balanceOf(from));
            }
            if (to != address(0) && to != address(this)) {
                pondManager.updateHolderEligibility(to, balanceOf(to));
            }
        }
    }

    function _applyLimitsAndProtections(address from, address to, uint256 amount)
        internal
        returns (uint256)
    {
        if (isLimitExempt[from] || isLimitExempt[to]) {
            return amount;
        }

        // Whale protection for sells
        if (automatedMarketMakerPairs[to] && !isWhaleExempt[from]) {
            amount = _applyWhaleProtection(from, amount);
        }

        // Check max transaction
        require(amount <= maxTxAmount, "Transfer amount exceeds max");

        // Check max wallet (for buys)
        if (automatedMarketMakerPairs[from] && to != address(uniswapV2Router)) {
            require(balanceOf(to) + amount <= maxWalletAmount, "Wallet would exceed max");
        }

        return amount;
    }

    function _calculateTax(address from, address to, uint256 amount)
        internal
        returns (uint256 netAmount, uint256 feeAmount, bool takeFeeFromRecipient)
    {
        netAmount = amount;

        if (excludedFromFees[from]) {
            return (netAmount, 0, false);
        }

        bool isBuy = automatedMarketMakerPairs[from];
        bool isSell = automatedMarketMakerPairs[to];
        if (!isBuy && !isSell) {
            return (netAmount, 0, false);
        }

        uint256 currentTaxRate = taxRate;

        if (
            !isWhaleExempt[from] && !isLimitExempt[from]
                && balanceOf(from) >= whaleConfig.whaleThreshold
        ) {
            currentTaxRate += whaleConfig.progressiveTaxRate;
            emit ProgressiveTaxApplied(from, taxRate, currentTaxRate);
        }
        if (!isWhaleExempt[to] && !isLimitExempt[to] && balanceOf(to) >= whaleConfig.whaleThreshold)
        {
            currentTaxRate += whaleConfig.progressiveTaxRate;
            emit ProgressiveTaxApplied(to, taxRate, currentTaxRate);
        }

        if (currentTaxRate > MAX_TAX_RATE) {
            currentTaxRate = MAX_TAX_RATE;
        }

        feeAmount = (amount * currentTaxRate) / TAX_DIVISOR;
        if (feeAmount == 0) {
            return (netAmount, 0, false);
        }

        takeFeeFromRecipient = isBuy;
        if (!takeFeeFromRecipient) {
            netAmount = amount - feeAmount;
        }

        return (netAmount, feeAmount, takeFeeFromRecipient);
    }

    // ==================== MEV Protection (Minimal) ====================

    function _applyMEVProtection(address from, address to) internal {
        // Simple sandwich protection only
        bool isBuy = automatedMarketMakerPairs[from];
        bool isSell = automatedMarketMakerPairs[to];

        if (isBuy) {
            // Record buy block for recipient
            lastBuyBlock[to] = block.number;
        }

        if (isSell && sandwichProtectionBlocks > 0) {
            // Only check if seller bought recently (sandwich attack prevention)
            require(
                block.number >= lastBuyBlock[from] + sandwichProtectionBlocks,
                "Please wait 1 block after buying"
            );
            emit MEVProtectionTriggered(from, "Sandwich protection");
        }
    }

    function _executeTokenTransfer(address from, address to, uint256 amount) internal {
        if (amount == 0) {
            return;
        }

        super._update(from, to, amount);
        _updateRewardCorrections(from, to, amount);
    }

    function _updateRewardCorrections(address from, address to, uint256 amount) internal {
        if (amount == 0) {
            return;
        }

        int256 magnifiedAmount = int256(magnifiedRewardsPerShare * amount);

        if (from == address(0)) {
            magnifiedRewardCorrections[to] -= magnifiedAmount;
        } else if (to == address(0)) {
            magnifiedRewardCorrections[from] += magnifiedAmount;
        } else {
            magnifiedRewardCorrections[from] += magnifiedAmount;
            magnifiedRewardCorrections[to] -= magnifiedAmount;
        }
    }

    function _addRewardExclusion(address account) internal {
        if (account == address(0) || rewardExclusionTracked[account]) {
            return;
        }

        rewardExclusionTracked[account] = true;
        rewardExclusionList.push(account);
    }

    function _syncRewardExclusion(address account, bool excluded) internal {
        if (account == address(0)) {
            return;
        }

        if (excluded) {
            _addRewardExclusion(account);
        }

        uint256 balance = balanceOf(account);
        int256 correction = int256(magnifiedRewardsPerShare * balance);
        magnifiedRewardCorrections[account] = -correction;
        withdrawnRewards[account] = 0;
    }

    // ==================== Whale Protection ====================

    function _applyWhaleProtection(address from, uint256 amount) internal returns (uint256) {
        uint256 balance = balanceOf(from);

        // Check if user is a whale
        if (balance < whaleConfig.whaleThreshold || isLimitExempt[from]) {
            return amount;
        }

        // Check cooldown
        require(
            block.number >= lastWhaleSell[from] + whaleConfig.sellCooldown,
            "Whale sell cooldown active"
        );

        // Calculate maximum allowed sell
        uint256 maxSell = (balance * whaleConfig.maxSellPercent) / 10000;

        require(amount <= maxSell, "Whale sell amount exceeds limit");

        lastWhaleSell[from] = block.number;
        return amount;
    }

    // ==================== Fee Processing ====================

    function _processFeesIfNeeded() internal {
        uint256 contractBalance = balanceOf(address(this));
        uint256 threshold = (totalSupply() * feeProcessingThreshold) / 100000000; // feeProcessingThreshold in basis points

        if (contractBalance >= threshold) {
            _processFees(contractBalance);
        }
    }

    function _processFees(uint256 amount) internal {
        // Reentrancy protection
        require(!processingFees, "Already processing fees");
        processingFees = true;

        // 1. First burn SELF_BURN portion (0.69%)
        uint256 selfBurnAmount = (amount * SELF_BURN_BPS) / TOTAL_BPS;
        if (selfBurnAmount > 0) {
            super._update(address(this), 0x000000000000000000000000000000000000dEaD, selfBurnAmount);
        }

        // 2. Calculate remaining amount for swapping to PEPE
        uint256 toSwap = amount - selfBurnAmount;

        if (toSwap == 0) {
            processingFees = false;
            return;
        }

        // 3. Swap all remaining to PEPE
        uint256 pepeReceived = _swapTokensForPepe(toSwap);
        if (pepeReceived == 0) {
            processingFees = false;
            return;
        }

        // 4. Distribute PEPE according to original ratios
        // Calculate each portion from received PEPE based on non-self-burn BPS
        uint256 nonSelfBurnBPS = TOTAL_BPS - SELF_BURN_BPS; // 6210

        uint256 pondPepe = (pepeReceived * POND_BPS) / nonSelfBurnBPS; // 6.9%
        uint256 burnPepe = (pepeReceived * PEPE_BURN_BPS) / nonSelfBurnBPS; // 0.69%
        uint256 rewardsPepe = (pepeReceived * REWARDS_BPS) / nonSelfBurnBPS; // 0.69%
        uint256 devPepe = (pepeReceived * DEV_BPS) / nonSelfBurnBPS; // 0.69%
        uint256 artPepe = (pepeReceived * ART_BPS) / nonSelfBurnBPS; // 0.03%

        // 5. Distribute PEPE

        if (pondPepe > 0) {
            pendingPondPepe += pondPepe;
        }

        uint256 pondSent = _forwardPondPepe();

        // PEPE burn (0.69%)
        if (burnPepe > 0) {
            PEPE.safeTransfer(0x000000000000000000000000000000000000dEaD, burnPepe);
        }

        // Holder rewards (0.69%)
        if (rewardsPepe > 0) {
            _distributeRewards(rewardsPepe);
        }

        // Dev wallet (0.42069%)
        if (devPepe > 0) {
            PEPE.safeTransfer(devWallet, devPepe);
        }

        // Art wallet (0.20241%)
        if (artPepe > 0) {
            PEPE.safeTransfer(artWallet, artPepe);
        }

        emit FeesProcessed(rewardsPepe, pondSent, devPepe + artPepe);

        // Reset reentrancy flag
        processingFees = false;
    }

    function _forwardPondPepe() internal returns (uint256 sent) {
        if (pendingPondPepe == 0) {
            return 0;
        }

        if (address(pondManager) == address(0) || pondManager.paused()) {
            return 0;
        }

        sent = pendingPondPepe;
        pendingPondPepe = 0;
        PEPE.safeTransfer(address(pondManager), sent);
        pondManager.addToPond(sent);
    }

    function _swapTokensForPepe(uint256 tokenAmount) internal virtual returns (uint256) {
        address[] memory path = new address[](3);
        path[0] = address(this);
        path[1] = WETH;
        path[2] = address(PEPE);

        uint256 pepeBalanceBefore = PEPE.balanceOf(address(this));

        // Get expected output amount for slippage protection
        uint256[] memory amounts = uniswapV2Router.getAmountsOut(tokenAmount, path);
        uint256 expectedPepe = amounts[2];

        // Use configurable slippage (default 1%)
        uint256 minPepe = expectedPepe - (expectedPepe * maxSlippageBPS / 10000);

        uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
            tokenAmount, minPepe, path, address(this), block.timestamp + 300
        );

        return PEPE.balanceOf(address(this)) - pepeBalanceBefore;
    }

    // ==================== Rewards System ====================

    function _distributeRewards(uint256 pepeAmount) internal {
        uint256 totalRewards = pepeAmount + pendingRewardsBuffer;
        if (totalRewards == 0) {
            return;
        }

        uint256 eligibleSupply = _getEligibleSupply();
        if (eligibleSupply == 0) {
            pendingRewardsBuffer = totalRewards;
            return;
        }

        pendingRewardsBuffer = 0;

        magnifiedRewardsPerShare += (totalRewards * REWARD_MAGNITUDE) / eligibleSupply;

        uint256 pepePerToken = (totalRewards * 1e18) / eligibleSupply;

        rewardSnapshots.push(
            RewardSnapshot({
                totalSupplySnapshot: eligibleSupply,
                pepePerToken: pepePerToken,
                timestamp: block.timestamp
            })
        );

        totalPepeDistributed += totalRewards;
        reservedPepeForRewards += totalRewards;

        emit RewardSnapshotTaken(rewardSnapshots.length - 1, pepePerToken, eligibleSupply);
    }

    function _getEligibleSupply() internal view returns (uint256) {
        uint256 total = totalSupply();

        for (uint256 i = 0; i < rewardExclusionList.length; i++) {
            address account = rewardExclusionList[i];
            if (excludedFromRewards[account]) {
                total -= balanceOf(account);
            }
        }

        return total;
    }

    function claimRewards() external nonReentrant {
        require(!excludedFromRewards[msg.sender], "Excluded from rewards");
        require(balanceOf(msg.sender) >= minBalanceForRewards, "Insufficient balance");
        require(
            block.timestamp >= lastRewardClaim[msg.sender] + rewardClaimCooldown,
            "Claim cooldown active"
        );

        uint256 pending = _calculatePendingRewards(msg.sender);
        require(pending > 0, "No rewards available");
        require(pending <= reservedPepeForRewards, "Insufficient PEPE reserves");

        lastRewardClaim[msg.sender] = block.timestamp;
        withdrawnRewards[msg.sender] += pending;
        totalPepeClaimed += pending;
        reservedPepeForRewards -= pending;

        PEPE.safeTransfer(msg.sender, pending);

        emit RewardsClaimed(msg.sender, pending);
    }

    function _accumulativeRewardsOf(address account) internal view returns (uint256) {
        int256 corrected = int256(magnifiedRewardsPerShare * balanceOf(account))
            + magnifiedRewardCorrections[account];
        if (corrected <= 0) {
            return 0;
        }

        return uint256(corrected) / REWARD_MAGNITUDE;
    }

    function _calculatePendingRewards(address user) internal view returns (uint256) {
        if (excludedFromRewards[user]) {
            return 0;
        }

        uint256 userBalance = balanceOf(user);
        if (userBalance < minBalanceForRewards) {
            return 0;
        }

        uint256 accumulative = _accumulativeRewardsOf(user);
        uint256 withdrawn = withdrawnRewards[user];

        if (accumulative <= withdrawn) {
            return 0;
        }

        return accumulative - withdrawn;
    }

    function pendingRewards(address user) external view returns (uint256) {
        return _calculatePendingRewards(user);
    }

    // ==================== Admin Functions ====================

    function setTaxRate(uint256 rate) external onlyOwner {
        require(rate <= MAX_TAX_RATE, "Tax rate too high");
        uint256 oldRate = taxRate;
        taxRate = rate;
        emit TaxRateUpdated(oldRate, rate);
    }

    function setExcludedFromFees(address account, bool excluded) external onlyOwner {
        excludedFromFees[account] = excluded;
    }

    function setLimitExempt(address account, bool exempt) external onlyOwner {
        isLimitExempt[account] = exempt;
        isWhaleExempt[account] = exempt;
        emit LimitExemptionUpdated(account, exempt);
    }

    function setExcludedFromRewards(address account, bool excluded) external onlyOwner {
        excludedFromRewards[account] = excluded;
        _syncRewardExclusion(account, excluded);
        emit RewardsExclusionUpdated(account, excluded);
    }

    function setAMM(address pair, bool value) external onlyOwner {
        automatedMarketMakerPairs[pair] = value;
    }

    function removeLimits() external onlyOwner {
        limitsInEffect = false;
    }

    function setWalletToWalletTransfers(bool disabled) external onlyOwner {
        walletToWalletTransfersDisabled = disabled;
    }

    function setLimits(uint256 maxTx, uint256 maxWallet) external onlyOwner {
        require(maxTx >= totalSupply() / 1000, "Max TX too low");
        require(maxWallet >= totalSupply() / 100, "Max wallet too low");
        maxTxAmount = maxTx;
        maxWalletAmount = maxWallet;
    }

    function setMinBalanceForRewards(uint256 rewardMin) external onlyOwner {
        minBalanceForRewards = rewardMin;
    }

    function setRewardCooldown(uint256 cooldown) external onlyOwner {
        rewardClaimCooldown = cooldown;
    }

    function setPondManager(address newPondManager) external onlyOwner {
        require(newPondManager != address(0), "Invalid pond manager");
        address oldManager = address(pondManager);
        pondManager = IPondManager(newPondManager);
        emit PondManagerUpdated(oldManager, newPondManager);

        if (oldManager != address(0)) {
            excludedFromRewards[oldManager] = false;
            _syncRewardExclusion(oldManager, false);
            emit RewardsExclusionUpdated(oldManager, false);
        }

        excludedFromRewards[newPondManager] = true;
        _syncRewardExclusion(newPondManager, true);
        emit RewardsExclusionUpdated(newPondManager, true);

        if (pendingPondPepe > 0) {
            _forwardPondPepe();
        }
    }

    // ==================== MEV Protection Admin ====================

    function setMEVProtection(bool enabled, uint256 sandwichBlocks) external onlyOwner {
        mevProtectionEnabled = enabled;
        sandwichProtectionBlocks = sandwichBlocks;
    }

    function setMaxSlippage(uint256 newSlippageBPS) external onlyOwner {
        require(newSlippageBPS >= 10 && newSlippageBPS <= 500, "Slippage must be 0.1% to 5%");
        maxSlippageBPS = newSlippageBPS;
    }

    // ==================== Whale Protection Admin ====================

    function setWhaleConfig(
        uint256 threshold,
        uint256 maxSellPercent,
        uint256 cooldownBlocks,
        uint256 progressiveTax
    ) external onlyOwner {
        require(maxSellPercent <= 10000, "Max sell too high");
        require(progressiveTax <= 1000, "Progressive tax too high");

        whaleConfig.whaleThreshold = threshold;
        whaleConfig.maxSellPercent = maxSellPercent;
        whaleConfig.sellCooldown = cooldownBlocks;
        whaleConfig.progressiveTaxRate = progressiveTax;
    }

    function setWhaleExempt(address account, bool exempt) external onlyOwner {
        isWhaleExempt[account] = exempt;
    }

    function batchSetWhaleExempt(address[] calldata accounts, bool exempt) external onlyOwner {
        for (uint256 i = 0; i < accounts.length; i++) {
            isWhaleExempt[accounts[i]] = exempt;
        }
    }

    function setFeeProcessingThreshold(uint256 newThreshold) external onlyOwner {
        require(
            newThreshold >= 100 && newThreshold <= 100000,
            "Threshold must be between 0.0001% and 0.1%"
        );
        feeProcessingThreshold = newThreshold;
    }

    function setDevWallet(address newDevWallet) external onlyOwner {
        require(newDevWallet != address(0), "Invalid dev wallet");
        address oldWallet = devWallet;
        devWallet = newDevWallet;

        // Update fee exclusion
        excludedFromFees[oldWallet] = false;
        excludedFromFees[newDevWallet] = true;

        excludedFromRewards[oldWallet] = false;
        _syncRewardExclusion(oldWallet, false);
        emit RewardsExclusionUpdated(oldWallet, false);

        excludedFromRewards[newDevWallet] = true;
        _syncRewardExclusion(newDevWallet, true);
        emit RewardsExclusionUpdated(newDevWallet, true);
    }

    function setArtWallet(address newArtWallet) external onlyOwner {
        require(newArtWallet != address(0), "Invalid art wallet");
        address oldWallet = artWallet;
        artWallet = newArtWallet;

        // Update fee exclusion
        excludedFromFees[oldWallet] = false;
        excludedFromFees[newArtWallet] = true;

        excludedFromRewards[oldWallet] = false;
        _syncRewardExclusion(oldWallet, false);
        emit RewardsExclusionUpdated(oldWallet, false);

        excludedFromRewards[newArtWallet] = true;
        _syncRewardExclusion(newArtWallet, true);
        emit RewardsExclusionUpdated(newArtWallet, true);
    }

    function setPepeToken(address newPepe) external onlyOwner {
        require(newPepe != address(0), "Invalid PEPE address");
        require(newPepe != address(this), "Cannot be self");

        PEPE = IERC20(newPepe);
    }

    function manualProcessFees() external onlyOwner {
        uint256 balance = balanceOf(address(this));
        if (balance > 0) {
            _processFees(balance);
        }
    }

    function depositExternalPondPepe(uint256 amount) external onlyOwner {
        require(amount > 0, "Amount zero");
        require(PEPE.balanceOf(address(this)) >= amount, "PEPE not received");

        pendingPondPepe += amount;
        uint256 forwarded = _forwardPondPepe();
        emit ExternalPondPepeDeposited(msg.sender, amount, forwarded);
    }

    function depositExternalRewardsPepe(uint256 amount) external onlyOwner {
        require(amount > 0, "Amount zero");
        require(PEPE.balanceOf(address(this)) >= amount, "PEPE not received");

        _distributeRewards(amount);
        emit ExternalRewardsPepeDeposited(msg.sender, amount);
    }

    function flushPendingPondPepe() external onlyOwner {
        require(address(pondManager) != address(0), "Pond manager not set");
        require(pendingPondPepe > 0, "No pending pond PEPE");
        require(!pondManager.paused(), "Pond manager paused");

        uint256 forwarded = _forwardPondPepe();
        require(forwarded > 0, "Forward failed");
    }

    function pause() external onlyOwner {
        _pause();
    }

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

    // ==================== View Functions ====================

    function getRewardSnapshots() external view returns (RewardSnapshot[] memory) {
        return rewardSnapshots;
    }

    function getRewardsReserveInfo()
        external
        view
        returns (
            uint256 totalReserved,
            uint256 totalDistributed,
            uint256 totalClaimed,
            uint256 contractPepeBalance
        )
    {
        return (
            reservedPepeForRewards,
            totalPepeDistributed,
            totalPepeClaimed,
            PEPE.balanceOf(address(this))
        );
    }

    function isProcessingFees() external view returns (bool) {
        return processingFees;
    }

    function getUserBasicStats(address user)
        external
        view
        returns (uint256 balance, uint256 pendingRewardsAmount, bool canClaim)
    {
        balance = balanceOf(user);
        pendingRewardsAmount = _calculatePendingRewards(user);
        canClaim = block.timestamp >= lastRewardClaim[user] + rewardClaimCooldown
            && pendingRewardsAmount > 0 && balance >= minBalanceForRewards;
    }

    receive() external payable { }
}
"
    },
    "@openzeppelin/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
"
    },
    "@openzeppelin/contracts/utils/Pausable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}
"
    },
    "@openzeppelin/contracts/utils/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

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

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

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/ERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.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}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * 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 ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

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

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual 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 default value returned by this function, unless
     * it's 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 returns (uint8) {
        return 18;
    }

    /// @inheritdoc IERC20
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual 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 `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /// @inheritdoc IERC20
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` 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 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * 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 `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` 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.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` 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.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, v

Tags:
ERC20, ERC165, Multisig, Burnable, Pausable, Swap, Liquidity, Upgradeable, Multi-Signature, Factory|addr:0xdc80d4cb7ff1fe185b4509c400aec5a7d17fb19a|verified:true|block:23463016|tx:0x1c1ca68ba3b2e751c39eb963f31e1b1821f7b88af8973a92592203f4ee482080|first_check:1759082553

Submitted on: 2025-09-28 20:02:33

Comments

Log in to comment.

No comments yet.