Skip to content
Verified contractPartialMIT

Ponzimon

Address0x40e8a12677ba7aeab28cfc7dbe70ffa8e817e548
Balance

0 ETH

 

Transactions

32

 

Compiler

solc 0.8.19

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.19+commit.7dd6d404
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Partialcreation code: no, runtime code: yes
Verified on Sourcify
Created in block
23,869,517
Creation transaction
0x24c8d08291…ae2c3b3158

contracts/PonziBattleArena.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IUniswap.sol";
import "./libraries/EvolutionSystem.sol";
import "./libraries/BattleSystem.sol";
import "./libraries/HolderTracker.sol";

/**
 * @title Ponzimon Battle Arena
 * @dev Pokemon-inspired token with evolution stages and faction wars
 * @custom:security-contact [email protected]
 */
contract Ponzimon is ReentrancyGuard {
    using EvolutionSystem for EvolutionSystem.EvolutionData;
    using BattleSystem for BattleSystem.SeasonData;
    using HolderTracker for address[];

    // ============ Constants ============
    
    string public constant name = "Ponzimon";
    string public constant symbol = "PONZI";
    uint8 public constant decimals = 18;
    uint256 private constant _totalSupply = 1000000 * 10**decimals;
    address public constant deadAddress = 0x000000000000000000000000000000000000dEaD;

    // ============ State Variables ============
    
    // ERC20
    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) private _allowances;
    mapping(address => bool) public isExcludedFromFee;
    mapping(address => bool) public isBot;

    // Evolution System
    EvolutionSystem.EvolutionData private evolutionData;
    mapping(address => bool) public hasBought;
    mapping(address => uint8) public walletLevel;
    mapping(address => uint256) public walletXP;
    mapping(address => address) public referrer;

    // Battle System
    BattleSystem.BattleState public battleState = BattleSystem.BattleState.ACTIVE;
    BattleSystem.SeasonData public currentSeason;
    uint256 public seasonDuration = 7 days;
    uint256 private factionAssignmentCounter = 0;
    uint256 private nonce = 0;

    mapping(BattleSystem.Faction => uint256) public factionVolume;
    mapping(BattleSystem.Faction => uint256) public factionMemberCount;
    mapping(address => BattleSystem.Faction) public userFaction;
    mapping(address => uint256) public battlePassExpiry;
    mapping(address => bool) public hasPurgeImmunity;
    mapping(address => bool) public isTraitor;
    mapping(address => uint256) public lastFactionJoinTime;
    mapping(address => uint256) public totalRewardsEarned;
    mapping(address => bool) public isInBottomPercentile;

    // Holder Tracking
    address[] public allHolders;
    mapping(address => uint256) public holderIndex;
    mapping(address => bool) public isHolder;
    mapping(BattleSystem.Faction => address[]) public factionHolders;
    mapping(BattleSystem.Faction => mapping(address => uint256)) public factionHolderIndex;

    // Uniswap & Economy
    address public owner;
    address public developmentWallet;
    IUniswapV2Router02 public uniswapV2Router;
    address public uniswapV2Pair;
    uint256 public arenaPrizePool;
    bool private inSwap = false;
    uint256 public swapThreshold = _totalSupply / 1000;
    uint256 public maxTxAmount;
    uint256 public maxWallet;

    // ============ Events ============
    
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
    event Evolved(uint8 stage);
    event WalletLevelUp(address wallet, uint8 newLevel);
    event LightningAirdrop(address winner, uint256 amount);
    event BurnSurge(uint256 amountBurned);
    event ReferralPaid(address referrer, address referee, uint256 amount);
    event FactionJoined(address user, BattleSystem.Faction faction);
    event BattlePassPurchased(address user, uint256 expiry);
    event SeasonCreated(uint256 seasonNumber, uint256 endTime);
    event PurgeExecuted(uint256 victims, uint256 valueLiquidated);
    event RewardsDistributed(BattleSystem.Faction winningFaction, uint256 totalDistributed);
    event ProphecyRevealed(BattleSystem.Faction prophesiedWinner);
    event BetrayalActivated(address traitor, uint256 reward);
    event FactionWarning(address user, string message);
    event PrizePoolDeposit(uint256 amount);
    event EmergencyWithdrawal(address to, uint256 amount);

    // ============ Modifiers ============
    
    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        _;
    }

    modifier battleActive() {
        require(battleState == BattleSystem.BattleState.ACTIVE, "Battle not active");
        _;
    }

    modifier lockTheSwap {
        inSwap = true;
        _;
        inSwap = false;
    }

    // ============ Constructor ============
    
    constructor() {
        owner = msg.sender;
        developmentWallet = msg.sender;
        
        // Initialize evolution data
        evolutionData.currentStage = 1;
        evolutionData.stageTriggers = [200, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 10000];
        evolutionData.buyTaxes = [40, 30, 25, 20, 15, 10, 8, 5, 3];
        evolutionData.sellTaxes = [60, 50, 40, 35, 30, 25, 20, 15, 10];
        evolutionData.stageRewards = [8, 12, 15, 20, 30, 35, 40, 50, 100];
        
        // Initialize Uniswap (Sepolia testnet address)
        IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0xeE567Fe1712Faf6149d80dA1E6934E354124CfE3);
        uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
        uniswapV2Router = _uniswapV2Router;
        
        // Exclude from fees
        isExcludedFromFee[owner] = true;
        isExcludedFromFee[address(this)] = true;
        isExcludedFromFee[address(uniswapV2Router)] = true;
        isExcludedFromFee[developmentWallet] = true;
        
        maxTxAmount = _totalSupply * 2 / 100;
        maxWallet = _totalSupply * 3 / 100;
        
        // Start season 1
        _startNewSeason();
        
        _balances[owner] = _totalSupply;
        HolderTracker.addHolder(allHolders, holderIndex, isHolder, owner, deadAddress);
        emit Transfer(address(0), owner, _totalSupply);
    }

    // ============ ERC20 Functions ============
    
    function totalSupply() public pure returns (uint256) { 
        return _totalSupply; 
    }
    
    function balanceOf(address account) public view returns (uint256) { 
        return _balances[account]; 
    }

    function transfer(address recipient, uint256 amount) public returns (bool) {
        _transfer(msg.sender, recipient, amount);
        return true;
    }

    function allowance(address _owner, address spender) public view returns (uint256) {
        return _allowances[_owner][spender];
    }

    function approve(address spender, uint256 amount) public returns (bool) {
        _approve(msg.sender, spender, amount);
        return true;
    }

    function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
        _transfer(sender, recipient, amount);
        uint256 currentAllowance = _allowances[sender][msg.sender];
        require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
        unchecked {
            _approve(sender, msg.sender, currentAllowance - amount);
        }
        return true;
    }

    function _approve(address _owner, address spender, uint256 amount) private {
        require(_owner != address(0), "ERC20: approve from zero address");
        require(spender != address(0), "ERC20: approve to zero address");
        _allowances[_owner][spender] = amount;
        emit Approval(_owner, spender, amount);
    }

    // ============ Main Transfer Logic ============
    
    function _transfer(address from, address to, uint256 amount) private {
        require(from != address(0), "ERC20: transfer from zero address");
        require(to != address(0), "ERC20: transfer to zero address");
        require(amount > 0, "Transfer amount must be greater than zero");
        require(!isBot[from] && !isBot[to], "Bots not allowed");

        // Max tx and wallet limits
        if(from != owner && to != owner) {
            require(amount <= maxTxAmount, "Transfer amount exceeds maxTxAmount");
            if(to != uniswapV2Pair && to != address(this) && to != address(uniswapV2Router)) {
                require(balanceOf(to) + amount <= maxWallet, "Transfer amount exceeds maxWallet");
            }
        }
        
        // Prevent bottom 20% from selling
        if(to == uniswapV2Pair && from != address(this)) {
            require(!isInBottomPercentile[from] || hasPurgeImmunity[from], "Bottom 20% cannot sell - face the purge");
        }
        
        bool takeFee = true;
        if(isExcludedFromFee[from] || isExcludedFromFee[to] || battleState != BattleSystem.BattleState.ACTIVE || inSwap) {
            takeFee = false;
        }
        
        // Swap collected tokens to ETH if threshold reached
        uint256 contractTokenBalance = balanceOf(address(this));
        bool canSwap = contractTokenBalance >= swapThreshold;
        
        if(canSwap && !inSwap && to == uniswapV2Pair && takeFee) {
            _swapAndLiquify(contractTokenBalance);
        }
        
        _tokenTransfer(from, to, amount, takeFee);
        
        // Update holder tracking
        if(balanceOf(from) == 0 && from != address(0)) {
            HolderTracker.removeHolder(allHolders, holderIndex, isHolder, from);
        }
        if(!isHolder[to] && to != address(0) && balanceOf(to) > 0) {
            HolderTracker.addHolder(allHolders, holderIndex, isHolder, to, deadAddress);
        }
        
        // Buy mechanics
        if(from == uniswapV2Pair && to != address(uniswapV2Router) && !isExcludedFromFee[to]) {
            if(!hasBought[to]) {
                hasBought[to] = true;
                evolutionData.uniqueBuyers++;
            }
            evolutionData.totalBuys++;
            _handleBuy(to, amount);
            _checkEvolution();
        }
        
        // Sell mechanics
        if(to == uniswapV2Pair && from != address(this) && !isExcludedFromFee[from]) {
            _handleSell(from, amount);
        }
        
        // Check season end
        if(BattleSystem.shouldEndSeason(currentSeason.endTime) && battleState == BattleSystem.BattleState.ACTIVE) {
            _endSeason();
        }
    }

    // ============ Buy Handler ============
    
    function _handleBuy(address buyer, uint256 amount) private {
        // Auto-join faction if new buyer
        if(userFaction[buyer] == BattleSystem.Faction.NONE) {
            BattleSystem.Faction assignedFaction = BattleSystem.assignFaction(factionAssignmentCounter);
            userFaction[buyer] = assignedFaction;
            lastFactionJoinTime[buyer] = block.timestamp;
            _addToFactionHolders(buyer, assignedFaction);
            factionAssignmentCounter++;
            emit FactionJoined(buyer, assignedFaction);
        }
        
        // Update volume tracking
        currentSeason.totalVolume += amount;
        factionVolume[userFaction[buyer]] += amount;
        factionMemberCount[userFaction[buyer]] = factionHolders[userFaction[buyer]].length;
        
        // Send warnings to losing factions
        BattleSystem.Faction leader = _getLeadingFaction();
        if(BattleSystem.isFactionLosing(
            userFaction[buyer],
            leader,
            factionVolume[userFaction[buyer]],
            factionVolume[leader]
        )) {
            emit FactionWarning(buyer, "YOUR FACTION IS LOSING - RISK OF PURGE INCREASED");
        }

        // Add XP with multiplier
        uint256 xpGain = amount * EvolutionSystem.getXPMultiplier(walletLevel[buyer]) / 100;
        
        // Stage 2+: Double XP
        if(evolutionData.currentStage >= 2) {
            xpGain = xpGain * 2;
        }
        
        walletXP[buyer] += xpGain;
        
        // Check for level up
        uint8 currentLevel = walletLevel[buyer];
        uint8 newLevel = EvolutionSystem.calculateLevel(walletXP[buyer]);
        if(newLevel > currentLevel) {
            walletLevel[buyer] = newLevel;
            emit WalletLevelUp(buyer, newLevel);
        }

        // Stage 5: Telepathy Rewards
        if(evolutionData.currentStage >= 5) {
            uint256 mirrorBonus = amount * 10 / 100;
            _balances[buyer] += mirrorBonus;
            emit Transfer(address(0), buyer, mirrorBonus);
        }

        // Stage 3: Lightning Airdrops
        if(evolutionData.currentStage >= 3 && evolutionData.totalBuys % 50 == 0) {
            _executeLightningAirdrop();
        }

        // Stage 6: Referral system
        if(evolutionData.currentStage >= 6 && referrer[buyer] != address(0)) {
            uint256 referralBonus = amount * 5 / 100;
            _balances[referrer[buyer]] += referralBonus;
            emit Transfer(address(0), referrer[buyer], referralBonus);
            emit ReferralPaid(referrer[buyer], buyer, referralBonus);
        }
    }

    // ============ Sell Handler ============
    
    function _handleSell(address seller, uint256 amount) private {
        // Stage 3: Sellers lose ALL XP
        if(evolutionData.currentStage >= 3) {
            walletXP[seller] = 0;
            walletLevel[seller] = 0;
        }

        // Traitor mechanics
        if(isTraitor[seller] && BattleSystem.shouldActivateBetrayal(_getRandom())) {
            uint256 betrayalBonus = amount * 10 / 100;
            _balances[seller] += betrayalBonus;
            emit Transfer(address(0), seller, betrayalBonus);
            emit BetrayalActivated(seller, betrayalBonus);
        }
    }

    // ============ Evolution System ============
    
    function _checkEvolution() private {
        if(EvolutionSystem.shouldEvolve(
            evolutionData.currentStage,
            evolutionData.totalBuys,
            evolutionData.stageTriggers
        )) {
            evolutionData.currentStage++;
            _distributeStageRewards();
            emit Evolved(evolutionData.currentStage);

            // Stage 4: Burn Surge
            if(evolutionData.currentStage >= 4) {
                uint256 burnAmount = balanceOf(address(this)) * 3 / 100;
                if(burnAmount > 0) {
                    _balances[address(this)] -= burnAmount;
                    _balances[deadAddress] += burnAmount;
                    emit Transfer(address(this), deadAddress, burnAmount);
                    emit BurnSurge(burnAmount);
                }
            }
        }
    }

    function _distributeStageRewards() private {
        uint256 rewardPool = _totalSupply * evolutionData.stageRewards[evolutionData.currentStage - 1] / 1000;
        
        if(evolutionData.currentStage == 9) {
            _distributeToLeveledHolders(rewardPool);
        } else {
            _distributeToTopHolders(rewardPool);
        }
    }

    function _distributeToLeveledHolders(uint256 rewardPool) private {
        uint256 count = 0;
        
        for(uint256 i = 0; i < allHolders.length && count < 50; i++) {
            address holder = allHolders[i];
            if(walletLevel[holder] >= 10 && balanceOf(holder) > 0) {
                uint256 share = rewardPool / 50;
                _balances[holder] += share;
                emit Transfer(address(0), holder, share);
                count++;
            }
        }
    }

    function _distributeToTopHolders(uint256 rewardPool) private {
        uint256 count = 0;
        
        for(uint256 i = 0; i < allHolders.length && count < 100; i++) {
            address holder = allHolders[i];
            if(balanceOf(holder) > 0 && holder != address(this) && holder != uniswapV2Pair) {
                uint256 share = rewardPool / 100;
                uint256 multiplier = EvolutionSystem.getStageMultiplier(evolutionData.currentStage, walletLevel[holder]);
                uint256 finalShare = share * multiplier / 100;
                _balances[holder] += finalShare;
                emit Transfer(address(0), holder, finalShare);
                count++;
            }
        }
    }

    function _executeLightningAirdrop() private {
        if(allHolders.length > 0) {
            uint256 randomIndex = _getRandom() % allHolders.length;
            address winner = allHolders[randomIndex];
            if(balanceOf(winner) > 0) {
                uint256 airdropAmount = _totalSupply * 1 / 1000;
                _balances[winner] += airdropAmount;
                emit Transfer(address(0), winner, airdropAmount);
                emit LightningAirdrop(winner, airdropAmount);
            }
        }
    }

    // ============ Token Transfer with Taxes ============
    
    function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
        uint256 taxAmount = 0;
        
        if(takeFee) {
            if(recipient == uniswapV2Pair) {
                taxAmount = amount * evolutionData.sellTaxes[evolutionData.currentStage - 1] / 100;
            } else if(sender == uniswapV2Pair) {
                uint256 buyTax = evolutionData.buyTaxes[evolutionData.currentStage - 1];
                
                // Apply faction discount
                BattleSystem.Faction buyerFaction = userFaction[recipient];
                if(buyerFaction != BattleSystem.Faction.NONE && buyerFaction == _getLeadingFaction()) {
                    buyTax = buyTax / 2;
                }
                taxAmount = amount * buyTax / 100;
            }
        }
        
        uint256 transferAmount = amount - taxAmount;
        _balances[sender] -= amount;
        _balances[recipient] += transferAmount;
        
        if(taxAmount > 0) {
            _balances[address(this)] += taxAmount;
            emit Transfer(sender, address(this), taxAmount);
        }
        
        emit Transfer(sender, recipient, transferAmount);
    }

    // ============ Swap & Liquidity ============
    
    function _swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
        uint256 lpTokens = contractTokenBalance * 50 / 100;
        uint256 prizeTokens = contractTokenBalance * 30 / 100;
        uint256 devTokens = contractTokenBalance - lpTokens - prizeTokens;

        if(prizeTokens > 0) {
            uint256 initialBalance = address(this).balance;
            _swapTokensForEth(prizeTokens);
            uint256 ethReceived = address(this).balance - initialBalance;
            arenaPrizePool += ethReceived;
            emit PrizePoolDeposit(ethReceived);
        }

        if(lpTokens > 0) {
            uint256 half = lpTokens / 2;
            uint256 otherHalf = lpTokens - half;
            
            uint256 initialBalance = address(this).balance;
            _swapTokensForEth(half);
            uint256 ethForLP = address(this).balance - initialBalance;
            
            if(ethForLP > 0) {
                _addLiquidity(otherHalf, ethForLP);
            }
        }

        if(devTokens > 0) {
            _swapTokensForEth(devTokens);
            uint256 devBalance = address(this).balance - arenaPrizePool;
            if(devBalance > 0) {
                payable(developmentWallet).transfer(devBalance);
            }
        }
    }

    function _swapTokensForEth(uint256 tokenAmount) private {
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = uniswapV2Router.WETH();

        _approve(address(this), address(uniswapV2Router), tokenAmount);

        try uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenAmount,
            0,
            path,
            address(this),
            block.timestamp
        ) {} catch {}
    }

    function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
        _approve(address(this), address(uniswapV2Router), tokenAmount);
        
        try uniswapV2Router.addLiquidityETH{value: ethAmount}(
            address(this),
            tokenAmount,
            0,
            0,
            owner,
            block.timestamp
        ) {} catch {}
    }

    // ============ Battle System Functions ============
    
    function purchaseBattlePass() external battleActive {
        require(userFaction[msg.sender] != BattleSystem.Faction.NONE, "Must join faction first");
        uint256 passCost = _totalSupply * 1 / 1000;
        require(balanceOf(msg.sender) >= passCost, "Insufficient balance");
        
        _burn(msg.sender, passCost);
        battlePassExpiry[msg.sender] = currentSeason.endTime;
        
        emit BattlePassPurchased(msg.sender, currentSeason.endTime);
    }

    function _endSeason() private {
        battleState = BattleSystem.BattleState.PURGING;
        _updateBottomPercentile();
        _executePurge();
        _distributeRewards();
        _startNewSeason();
    }

    function _updateBottomPercentile() private {
        // Reset all
        for(uint256 i = 0; i < allHolders.length; i++) {
            isInBottomPercentile[allHolders[i]] = false;
        }

        if(allHolders.length <= 5) return;

        // Create arrays for sorting
        address[] memory sortedHolders = new address[](allHolders.length);
        uint256[] memory balances = new uint256[](allHolders.length);
        
        for(uint256 i = 0; i < allHolders.length; i++) {
            sortedHolders[i] = allHolders[i];
            balances[i] = balanceOf(allHolders[i]);
        }

        // Sort using library
        HolderTracker.sortHoldersByBalance(sortedHolders, balances, 200);

        // Mark bottom 20%
        uint256 purgeCount = HolderTracker.getPurgeCount(sortedHolders.length);
        for(uint256 i = 0; i < purgeCount && i < sortedHolders.length; i++) {
            if(!hasPurgeImmunity[sortedHolders[i]]) {
                isInBottomPercentile[sortedHolders[i]] = true;
            }
        }
    }

    function _executePurge() private nonReentrant {
        uint256 totalVictims = 0;
        uint256 totalLiquidated = 0;
        
        for(uint256 i = 0; i < allHolders.length && totalVictims < 100; i++) {
            address victim = allHolders[i];
            
            if(isInBottomPercentile[victim] && balanceOf(victim) > 0) {
                uint256 victimBalance = balanceOf(victim);
                totalLiquidated += victimBalance;
                totalVictims++;
                
                _balances[victim] = 0;
                _balances[address(this)] += victimBalance;
                emit Transfer(victim, address(this), victimBalance);
                
                HolderTracker.removeHolder(allHolders, holderIndex, isHolder, victim);
                _removeFromFactionHolders(victim, userFaction[victim]);
                userFaction[victim] = BattleSystem.Faction.NONE;
            }
        }
        
        if(totalLiquidated > 0) {
            _swapTokensForEth(totalLiquidated);
        }
        
        emit PurgeExecuted(totalVictims, totalLiquidated);
    }

    function _distributeRewards() private nonReentrant {
        BattleSystem.Faction winningFaction = _getLeadingFaction();
        uint256 totalToDistribute = arenaPrizePool;
        
        if(winningFaction != BattleSystem.Faction.NONE && totalToDistribute > 0) {
            address[] storage winners = factionHolders[winningFaction];
            address[] memory qualifiedWinners = new address[](50);
            uint256 qualifiedCount = 0;
            
            for(uint256 i = 0; i < winners.length && qualifiedCount < 50; i++) {
                if(battlePassExpiry[winners[i]] >= currentSeason.endTime && balanceOf(winners[i]) > 0) {
                    qualifiedWinners[qualifiedCount] = winners[i];
                    qualifiedCount++;
                }
            }
            
            if(qualifiedCount > 0) {
                uint256 sharePerWinner = totalToDistribute / qualifiedCount;
                
                if(winningFaction == currentSeason.prophesiedWinner) {
                    sharePerWinner = sharePerWinner * 2;
                }
                
                for(uint256 i = 0; i < qualifiedCount; i++) {
                    address winner = qualifiedWinners[i];
                    (bool success, ) = payable(winner).call{value: sharePerWinner}("");
                    if(success) {
                        totalRewardsEarned[winner] += sharePerWinner;
                    }
                }
            }
        }
        
        arenaPrizePool = 0;
        emit RewardsDistributed(winningFaction, totalToDistribute);
    }

    function _startNewSeason() private {
        currentSeason.number++;
        currentSeason.startTime = block.timestamp;
        currentSeason.endTime = block.timestamp + seasonDuration;
        currentSeason.prophesiedWinner = BattleSystem.getRandomFaction(nonce);
        nonce++;
        
        battleState = BattleSystem.BattleState.ACTIVE;
        
        emit SeasonCreated(currentSeason.number, currentSeason.endTime);
        emit ProphecyRevealed(currentSeason.prophesiedWinner);
    }

    // ============ Helper Functions ============
    
    function _getLeadingFaction() private view returns (BattleSystem.Faction) {
        return BattleSystem.getLeadingFaction(
            factionVolume[BattleSystem.Faction.FIRE],
            factionVolume[BattleSystem.Faction.WATER],
            factionVolume[BattleSystem.Faction.ELECTRIC]
        );
    }

    function _getRandom() private returns (uint256) {
        nonce++;
        return uint256(keccak256(abi.encodePacked(
            block.timestamp,
            block.prevrandao,
            msg.sender,
            nonce,
            allHolders.length
        )));
    }

    function _addToFactionHolders(address holder, BattleSystem.Faction faction) private {
        if(faction == BattleSystem.Faction.NONE) return;
        factionHolderIndex[faction][holder] = factionHolders[faction].length;
        factionHolders[faction].push(holder);
    }

    function _removeFromFactionHolders(address holder, BattleSystem.Faction faction) private {
        if(faction == BattleSystem.Faction.NONE) return;
        
        uint256 index = factionHolderIndex[faction][holder];
        uint256 lastIndex = factionHolders[faction].length - 1;
        
        if(index != lastIndex) {
            address lastHolder = factionHolders[faction][lastIndex];
            factionHolders[faction][index] = lastHolder;
            factionHolderIndex[faction][lastHolder] = index;
        }
        
        factionHolders[faction].pop();
        delete factionHolderIndex[faction][holder];
    }

    function _burn(address account, uint256 amount) private {
        require(_balances[account] >= amount, "Burn amount exceeds balance");
        _balances[account] -= amount;
        _balances[deadAddress] += amount;
        emit Transfer(account, deadAddress, amount);
    }

    // ============ Admin Functions ============
    
    function setReferrer(address _referrer) external {
        require(referrer[msg.sender] == address(0), "Referrer already set");
        require(_referrer != msg.sender, "Cannot refer yourself");
        referrer[msg.sender] = _referrer;
    }

    function setTraitor(address user, bool status) external onlyOwner {
        isTraitor[user] = status;
    }

    function grantPurgeImmunity(address user) external onlyOwner {
        hasPurgeImmunity[user] = true;
    }

    function setBots(address[] memory bots, bool status) external onlyOwner {
        for(uint256 i = 0; i < bots.length; i++) {
            isBot[bots[i]] = status;
        }
    }

    function excludeFromFee(address account) external onlyOwner {
        isExcludedFromFee[account] = true;
    }

    function includeInFee(address account) external onlyOwner {
        isExcludedFromFee[account] = false;
    }

    function setLimits(uint256 _maxTx, uint256 _maxWallet) external onlyOwner {
        maxTxAmount = _maxTx;
        maxWallet = _maxWallet;
    }

    function setSwapThreshold(uint256 _threshold) external onlyOwner {
        swapThreshold = _threshold;
    }

    function setDevelopmentWallet(address _dev) external onlyOwner {
        developmentWallet = _dev;
    }

    function manualEndSeason() external onlyOwner {
        _endSeason();
    }

    function manualEvolve() external onlyOwner {
        _checkEvolution();
    }

    function emergencyWithdrawPrizePool(address payable to, uint256 amount) external onlyOwner {
        require(amount <= arenaPrizePool, "Amount exceeds prize pool");
        require(to != address(0), "Invalid address");
        
        arenaPrizePool -= amount;
        (bool success, ) = to.call{value: amount}("");
        require(success, "Transfer failed");
        
        emit EmergencyWithdrawal(to, amount);
    }

    function withdrawStuckETH() external onlyOwner {
        uint256 balance = address(this).balance - arenaPrizePool;
        require(balance > 0, "No stuck ETH");
        payable(owner).transfer(balance);
    }

    function emergencyPause() external onlyOwner {
        battleState = BattleSystem.BattleState.PURGING;
    }

    function resumeBattle() external onlyOwner {
        battleState = BattleSystem.BattleState.ACTIVE;
    }

    // ============ View Functions ============
    
    function isAddressInDanger(address account) external view returns (bool) {
        return isInBottomPercentile[account];
    }

    function getFactionStats(BattleSystem.Faction faction) external view returns (uint256 volume, uint256 memberCount) {
        return (factionVolume[faction], factionHolders[faction].length);
    }

    function getCurrentStageInfo() external view returns (
        uint8 stage,
        uint256 buysUntilNext,
        uint8 currentBuyTax,
        uint8 currentSellTax
    ) {
        return EvolutionSystem.getCurrentStageInfo(evolutionData);
    }

    function totalBuys() external view returns (uint256) {
        return evolutionData.totalBuys;
    }

    function uniqueBuyers() external view returns (uint256) {
        return evolutionData.uniqueBuyers;
    }

    function currentStage() external view returns (uint8) {
        return evolutionData.currentStage;
    }

    receive() external payable {}
}

@openzeppelin/contracts/security/ReentrancyGuard.sol

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

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

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

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

contracts/interfaces/IUniswap.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

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

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

contracts/libraries/BattleSystem.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/**
 * @title BattleSystem
 * @dev Manages faction wars, seasons, and purge mechanics
 */
library BattleSystem {
    enum Faction { NONE, FIRE, WATER, ELECTRIC }
    enum BattleState { ACTIVE, PURGING, DISTRIBUTING }
    
    uint256 constant PURGE_PERCENTAGE = 20;
    
    struct SeasonData {
        uint256 number;
        uint256 startTime;
        uint256 endTime;
        uint256 totalVolume;
        Faction prophesiedWinner;
        bool purgeExecuted;
        bool rewardsDistributed;
    }
    
    /**
     * @dev Calculate if a faction is losing (< 80% of leader's volume)
     */
    function isFactionLosing(
        Faction faction,
        Faction leader,
        uint256 factionVolume,
        uint256 leaderVolume
    ) internal pure returns (bool) {
        return faction != leader && factionVolume < leaderVolume * 80 / 100;
    }
    
    /**
     * @dev Get leading faction based on volume
     */
    function getLeadingFaction(
        uint256 fireVolume,
        uint256 waterVolume,
        uint256 electricVolume
    ) internal pure returns (Faction) {
        if(fireVolume >= waterVolume && fireVolume >= electricVolume) return Faction.FIRE;
        if(waterVolume >= fireVolume && waterVolume >= electricVolume) return Faction.WATER;
        return Faction.ELECTRIC;
    }
    
    /**
     * @dev Check if season should end
     */
    function shouldEndSeason(uint256 endTime) internal view returns (bool) {
        return block.timestamp >= endTime;
    }
    
    /**
     * @dev Generate random faction for prophecy
     */
    function getRandomFaction(uint256 nonce) internal view returns (Faction) {
        uint256 random = uint256(keccak256(abi.encodePacked(
            block.timestamp,
            block.prevrandao,
            msg.sender,
            nonce
        ))) % 3;
        return Faction(random + 1);
    }
    
    /**
     * @dev Assign faction sequentially
     */
    function assignFaction(uint256 counter) internal pure returns (Faction) {
        return Faction((counter % 3) + 1);
    }
    
    /**
     * @dev Calculate betrayal activation (5% chance)
     */
    function shouldActivateBetrayal(uint256 randomSeed) internal pure returns (bool) {
        return randomSeed % 100 < 5;
    }
}

contracts/libraries/EvolutionSystem.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/**
 * @title EvolutionSystem
 * @dev Manages token evolution stages, XP, and level progression
 */
library EvolutionSystem {
    struct EvolutionData {
        uint8 currentStage;
        uint256 totalBuys;
        uint256 uniqueBuyers;
        uint256[9] stageTriggers;
        uint8[9] buyTaxes;
        uint8[9] sellTaxes;
        uint8[9] stageRewards;
    }
    
    /**
     * @dev Calculate wallet level based on XP
     */
    function calculateLevel(uint256 xp) internal pure returns (uint8) {
        if(xp >= 100000 * 10**18) return 10;
        if(xp >= 50000 * 10**18) return 9;
        if(xp >= 25000 * 10**18) return 8;
        if(xp >= 10000 * 10**18) return 7;
        if(xp >= 5000 * 10**18) return 6;
        if(xp >= 2500 * 10**18) return 5;
        if(xp >= 1000 * 10**18) return 4;
        if(xp >= 500 * 10**18) return 3;
        if(xp >= 100 * 10**18) return 2;
        if(xp >= 10 * 10**18) return 1;
        return 0;
    }
    
    /**
     * @dev Get XP multiplier based on wallet level
     */
    function getXPMultiplier(uint8 level) internal pure returns (uint256) {
        if(level >= 7) return 500;
        if(level >= 3) return 300;
        if(level >= 1) return 200;
        return 100;
    }
    
    /**
     * @dev Get stage-based reward multiplier
     */
    function getStageMultiplier(uint8 currentStage, uint8 walletLevel) internal pure returns (uint256) {
        if(currentStage == 9 && walletLevel >= 10) return 200;
        return 100;
    }
    
    /**
     * @dev Check if evolution should occur
     */
    function shouldEvolve(
        uint8 currentStage,
        uint256 totalBuys,
        uint256[9] memory stageTriggers
    ) internal pure returns (bool) {
        return currentStage < 9 && totalBuys >= stageTriggers[currentStage - 1];
    }
    
    /**
     * @dev Get current stage info
     */
    function getCurrentStageInfo(
        EvolutionData memory data
    ) internal pure returns (
        uint8 stage,
        uint256 buysUntilNext,
        uint8 currentBuyTax,
        uint8 currentSellTax
    ) {
        stage = data.currentStage;
        uint256 nextTrigger = stage < 9 ? data.stageTriggers[stage - 1] : 0;
        buysUntilNext = nextTrigger > data.totalBuys ? nextTrigger - data.totalBuys : 0;
        currentBuyTax = data.buyTaxes[stage - 1];
        currentSellTax = data.sellTaxes[stage - 1];
    }
}

contracts/libraries/HolderTracker.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/**
 * @title HolderTracker
 * @dev Manages holder tracking and array operations
 */
library HolderTracker {
    /**
     * @dev Add holder to tracking array
     */
    function addHolder(
        address[] storage allHolders,
        mapping(address => uint256) storage holderIndex,
        mapping(address => bool) storage isHolder,
        address holder,
        address deadAddress
    ) internal {
        if(!isHolder[holder] && holder != address(0) && holder != deadAddress) {
            isHolder[holder] = true;
            holderIndex[holder] = allHolders.length;
            allHolders.push(holder);
        }
    }
    
    /**
     * @dev Remove holder from tracking array
     */
    function removeHolder(
        address[] storage allHolders,
        mapping(address => uint256) storage holderIndex,
        mapping(address => bool) storage isHolder,
        address holder
    ) internal {
        if(isHolder[holder]) {
            uint256 index = holderIndex[holder];
            uint256 lastIndex = allHolders.length - 1;
            
            if(index != lastIndex) {
                address lastHolder = allHolders[lastIndex];
                allHolders[index] = lastHolder;
                holderIndex[lastHolder] = index;
            }
            
            allHolders.pop();
            delete holderIndex[holder];
            isHolder[holder] = false;
        }
    }
    
    /**
     * @dev Sort holders by balance (selection sort, limited iterations)
     */
    function sortHoldersByBalance(
        address[] memory holders,
        uint256[] memory balances,
        uint256 maxIterations
    ) internal pure {
        uint256 length = holders.length < maxIterations ? holders.length : maxIterations;
        
        for(uint256 i = 0; i < length; i++) {
            for(uint256 j = i + 1; j < length; j++) {
                if(balances[i] > balances[j]) {
                    // Swap balances
                    uint256 tempBalance = balances[i];
                    balances[i] = balances[j];
                    balances[j] = tempBalance;
                    
                    // Swap addresses
                    address tempAddress = holders[i];
                    holders[i] = holders[j];
                    holders[j] = tempAddress;
                }
            }
        }
    }
    
    /**
     * @dev Calculate purge count (bottom 20%)
     */
    function getPurgeCount(uint256 totalHolders) internal pure returns (uint256) {
        return (totalHolders * 20) / 100; // PURGE_PERCENTAGE = 20
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.