// File: ChainFactory_ERC20.sol



/*

  MEGAToken

  Become a holder of MEGAToken. Official currency of the future MEGA Wallet.

  Web: https://megatoken.tech/
  X: https://twitter.com/MEGATokenApp

*/

// SPDX-License-Identifier: MIT

pragma solidity 0.8.23;

import "./CF_Ownable.sol";
import "./CF_Common.sol";
import "./CF_ERC20.sol";
import "./CF_Pausable.sol";
import "./CF_Taxable.sol";
import "./CF_DEXRouterV2.sol";
import "./CF_HolderList.sol";

contract ChainFactory_ERC20 is CF_Ownable, CF_Common, CF_ERC20, CF_Pausable, CF_Taxable, CF_DEXRouterV2, CF_HolderList {
  constructor() {
    _name = unicode"MEGAToken";
    _symbol = unicode"MEGA";
    _decimals = 18;
    _totalSupply = 55000000000000000000000000; // 55,000,000 MEGA
    _transferOwnership(0xFcF91DF83E05823B50c6d7549077a7e2894Fdd00);
    _transferInitialSupply(0xFcF91DF83E05823B50c6d7549077a7e2894Fdd00, 100000); // 100%
    _setDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 0xFcF91DF83E05823B50c6d7549077a7e2894Fdd00);
    _swapEnabled = true;
    _setMinSwapPercent(500); // 0.5% of totalSupply
    _setMinTaxDistributionPercent(500); // 0.5% of totalSupply
    _setTaxBeneficiary(0, 0xFcF91DF83E05823B50c6d7549077a7e2894Fdd00, [ uint24(500), uint24(1000), uint24(10000) ]);
    _domainSeparator = keccak256(abi.encode(keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(_name)), keccak256(bytes("1")), block.chainid, address(this)));
    _initialized = true;

    _holder[address(this)].exists = true;
    _holders.push(address(this));
  }

  function _transfer(address from, address to, uint256 amount) internal virtual override {
    require(!_paused, "Paused");

    if (!_distributing && !_swapping && (from != _dex.pair && from != _dex.router)) {
      _autoSwap(false);
      _autoTaxDistribute(false);
    }

    if (amount > 0 && from != _owner && to != _owner && from != address(this) && to != address(this) && to != _dex.router) {
      require((from != _dex.pair && to != _dex.pair) || ((from == _dex.pair || to == _dex.pair) && _tradingEnabled > 0), "Trading disabled");

      unchecked {
        if (!_suspendTaxes && !_distributing && !_swapping) {
          uint256 appliedTax;
          uint8 taxType;

          if (from == _dex.pair || to == _dex.pair) { taxType = from == _dex.pair ? 1 : 2; }

          for (uint8 i; i < 5; i++) {
            uint256 percent = uint256(taxType > 0 ? (taxType == 1 ? _taxBeneficiary[i].percent[1] : _taxBeneficiary[i].percent[2]) : _taxBeneficiary[i].percent[0]);

            if (percent == 0) { continue; }

            uint256 taxAmount = _percentage(amount, percent);

            super._transfer(from, address(this), taxAmount);

            if (_taxBeneficiary[i].account == _dex.pair) {
              _amountForLiquidity += taxAmount;
            } else {
              _taxBeneficiary[i].unclaimed += taxAmount;
              _amountForTaxDistribution += taxAmount;
            }

            appliedTax += taxAmount;
          }

          if (appliedTax > 0) {
            _totalTaxCollected += appliedTax;

            amount -= appliedTax;
          }
        }
      }
    }

    super._transfer(from, to, amount);

    if (amount > 0 && !_holder[to].exists) {
      _holder[to].exists = true;
      _holders.push(to);
    }
  }

  function _transferInitialSupply(address account, uint24 percent) private {
    require(!_initialized);

    uint256 amount = _percentage(_totalSupply, uint256(percent));
    _balance[account] = amount;
    _holder[account].exists = true;
    _holders.push(account);

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

  /// @notice Returns a list specifying the renounce status of each feature
  function renounced() external view returns (bool Pausable, bool Taxable, bool DEXRouterV2) {
    return (_renounced.Pausable, _renounced.Taxable, _renounced.DEXRouterV2);
  }

  /// @notice Returns basic information about this Smart-Contract
  function info() external view returns (string memory name, string memory symbol, uint8 decimals, address owner, uint256 totalSupply, string memory version) {
    return (_name, _symbol, _decimals, _owner, _totalSupply, _version);
  }

  receive() external payable { }
  fallback() external payable { }
}

/*
   ________          _       ______           __                  
  / ____/ /_  ____ _(_)___  / ____/___ ______/ /_____  _______  __
 / /   / __ \/ __ `/ / __ \/ /_  / __ `/ ___/ __/ __ \/ ___/ / / /
/ /___/ / / / /_/ / / / / / __/ / /_/ / /__/ /_/ /_/ / /  / /_/ / 
\____/_/ /_/\__,_/_/_/ /_/_/    \__,_/\___/\__/\____/_/   \__, /  
                                                         /____/   
  Smart-Contract generated and deployed by ChainFactory

  Web:      https://chainfactory.app/
  X:        https://x.com/ChainFactoryApp
  Telegram: https://t.me/ChainFactory
  Discord:  https://discord.gg/fpjxD39v3k
  YouTube:  https://youtube.com/@UpfrontDeFi

  By using this Smart-Contract generated and deployed by ChainFactory,
  you acknowledge and agree that ChainFactory shall not be liable for any
  damages arising from the use of this Smart-Contract, including but not
  limited to any damages resulting from any malicious or illegal use of
  the Smart-Contract by any third party or by the owner.

  The owner of the Smart-Contract generated by ChainFactory agrees not to
  misuse the Smart-Contract, including but not limited to:

  - Using the Smart-Contract to engage in any illegal or fraudulent
    activity, including but not limited to scams, theft, or money
    laundering.

  - Using the Smart-Contract in any manner that could cause harm to
    others, including but not limited to disrupting financial
    markets or causing financial loss to others.

  - Using the Smart-Contract to infringe upon the intellectual
    property rights of others, including but not limited to
    copyright, trademark, or patent infringement.

  The owner of the Smart-Contract generated by ChainFactory acknowledges
  that any misuse of the Smart-Contract may result in legal action,
  and agrees to indemnify and hold harmless ChainFactory from any and all
  claims, damages, or expenses arising from any such misuse.

*/

// File: CF_Ownable.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.23;

abstract contract CF_Ownable {
  address internal _owner;

  event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

  modifier onlyOwner() {
    require(_owner == msg.sender, "Unauthorized");

    _;
  }

  function owner() external view returns (address) {
    return _owner;
  }

  function renounceOwnership() external onlyOwner {
    _transferOwnership(address(0));
  }

  function transferOwnership(address newOwner) external onlyOwner {
    require(newOwner != address(0));

    _transferOwnership(newOwner);
  }

  function _transferOwnership(address newOwner) internal {
    address oldOwner = _owner;
    _owner = newOwner;

    emit OwnershipTransferred(oldOwner, newOwner);
  }
}

// File: CF_Common.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.23;

import "./IDEXV2.sol";

abstract contract CF_Common {
  string internal constant _version = "1.0.0";

  mapping(address => uint256) internal _balance;
  mapping(address => mapping(address => uint256)) internal _allowance;
  mapping(address => holderAccount) internal _holder;
  mapping(uint8 => taxBeneficiary) internal _taxBeneficiary;

  address[] internal _holders;

  bool internal _swapEnabled;
  bool internal _swapping;
  bool internal _paused;
  bool internal _suspendTaxes;
  bool internal _distributing;
  bool internal immutable _initialized;

  uint8 internal immutable _decimals;
  uint24 internal constant _denominator = 1000;
  uint24 internal _totalTxTax;
  uint24 internal _totalBuyTax;
  uint24 internal _totalSellTax;
  uint24 internal _minTaxDistributionPercent;
  uint24 internal _minSwapPercent;
  uint32 internal _lastTaxDistribution;
  uint32 internal _tradingEnabled;
  uint32 internal _lastSwap;
  uint256 internal _totalSupply;
  uint256 internal _totalTaxCollected;
  uint256 internal _minTaxDistributionAmount;
  uint256 internal _amountForTaxDistribution;
  uint256 internal _minSwapAmount;
  uint256 internal _amountForLiquidity;

  struct Renounced {
    bool Pausable;
    bool Taxable;
    bool DEXRouterV2;
  }

  struct holderAccount {
    bool exists;
  }

  struct taxBeneficiary {
    bool exists;
    address account;
    uint24[3] percent; // 0: tx, 1: buy, 2: sell
    uint256 unclaimed;
  }

  struct DEXRouterV2 {
    address router;
    address pair;
    address WETH;
    address receiver;
  }

  Renounced internal _renounced;
  DEXRouterV2 internal _dex;

  function _percentage(uint256 amount, uint256 bps) internal pure returns (uint256) {
    unchecked {
      return (amount * bps) / (100 * uint256(_denominator));
    }
  }

  function _timestamp() internal view returns (uint32) {
    unchecked {
      return uint32(block.timestamp % 2**32);
    }
  }

  function denominator() external pure returns (uint24) {
    return _denominator;
  }

  function version() external pure returns (string memory) {
    return _version;
  }
}

// File: CF_ERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.23;

import "./CF_Common.sol";

abstract contract CF_ERC20 is CF_Common {
  string internal _name;
  string internal _symbol;
  bytes32 internal _domainSeparator;
  bytes32 private constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
  mapping(address => uint256) private _nonces;

  event Transfer(address indexed from, address indexed to, uint256 value);
  event Approval(address indexed owner, address indexed spender, uint256 value);

  function name() external view returns (string memory) {
    return _name;
  }

  function symbol() external view returns (string memory) {
    return _symbol;
  }

  function decimals() external view returns (uint8) {
    return _decimals;
  }

  function totalSupply() external view returns (uint256) {
    return _totalSupply;
  }

  function balanceOf(address account) external view returns (uint256) {
    return _balance[account];
  }

  function allowance(address owner, address spender) public view returns (uint256) {
    return _allowance[owner][spender];
  }

  function approve(address spender, uint256 amount) external returns (bool) {
    _approve(msg.sender, spender, amount);

    return true;
  }

  function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
    require(deadline >= block.timestamp, "Expired signature");

    unchecked {
      bytes32 digest = keccak256(abi.encodePacked(hex"1901", _domainSeparator, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _nonces[owner]++, deadline))));
      address recoveredAddress = ecrecover(digest, v, r, s);

      require(recoveredAddress != address(0) && recoveredAddress == owner, "Invalid signature");
    }

    _approve(owner, spender, value);
  }

  function nonces(address owner) external view returns (uint256) {
    return _nonces[owner];
  }

  function DOMAIN_SEPARATOR() external view returns (bytes32) {
    return _domainSeparator;
  }

  function transfer(address to, uint256 amount) external returns (bool) {
    _transfer(msg.sender, to, amount);

    return true;
  }

  function transferFrom(address from, address to, uint256 amount) external returns (bool) {
    _spendAllowance(from, msg.sender, amount);
    _transfer(from, to, amount);

    return true;
  }

  function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
    unchecked {
      _approve(msg.sender, spender, allowance(msg.sender, spender) + addedValue);
    }

    return true;
  }

  function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
    uint256 currentAllowance = allowance(msg.sender, spender);

    require(currentAllowance >= subtractedValue, "Negative allowance");

    unchecked {
      _approve(msg.sender, spender, currentAllowance - subtractedValue);
    }

    return true;
  }

  function _approve(address owner, address spender, uint256 amount) internal {
    _allowance[owner][spender] = amount;

    emit Approval(owner, spender, amount);
  }

  function _spendAllowance(address owner, address spender, uint256 amount) internal {
    uint256 currentAllowance = allowance(owner, spender);

    require(currentAllowance >= amount, "Insufficient allowance");

    unchecked {
      _approve(owner, spender, currentAllowance - amount);
    }
  }

  function _transfer(address from, address to, uint256 amount) internal virtual {
    require(from != address(0) && to != address(0), "Transfer from/to zero address");
    require(_balance[from] >= amount, "Exceeds balance");

    if (amount > 0) {
      unchecked {
        _balance[from] -= amount;
        _balance[to] += amount;
      }
    }

    emit Transfer(from, to, amount);
  }
}

// File: CF_Pausable.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.23;

import "./CF_Ownable.sol";
import "./CF_Common.sol";

abstract contract CF_Pausable is CF_Ownable, CF_Common {
  event Paused(bool status);
  event RenouncedPausable();

  /// @notice Permanently renounce and prevent the owner from being able to pause the Smart-Contract
  /// @dev Existing settings will continue to be effective
  function renouncePausable() external onlyOwner {
    _renounced.Pausable = true;

    emit RenouncedPausable();
  }

  /// @notice Check if the Smart-Contract is paused
  function isPaused() external view returns (bool) {
    return _paused;
  }

  function pause(bool status) external onlyOwner {
    require(!_renounced.Pausable);
    require(_paused != status);

    _paused = status;

    emit Paused(status);
  }
}

// File: CF_Taxable.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.23;

import "./CF_Ownable.sol";
import "./CF_Common.sol";
import "./CF_ERC20.sol";

abstract contract CF_Taxable is CF_Ownable, CF_Common, CF_ERC20 {
  event SetTaxBeneficiary(uint8 slot, address account, uint24[3] percent);
  event TaxDistributed(uint256 amount);
  event RenouncedTaxable();

  struct taxBeneficiaryView {
    address account;
    uint24[3] percent;
    uint256 unclaimed;
  }

  modifier lockDistributing {
    _distributing = true;
    _;
    _distributing = false;
  }

  /// @notice Permanently renounce and prevent the owner from being able to update the tax features
  /// @dev Existing settings will continue to be effective
  function renounceTaxable() external onlyOwner {
    _renounced.Taxable = true;

    emit RenouncedTaxable();
  }

  /// @notice Total amount of taxes collected so far
  function totalTaxCollected() external view returns (uint256) {
    return _totalTaxCollected;
  }

  /// @notice Tax applied per transfer
  /// @dev Taking in consideration your wallet address
  function txTax() external view returns (uint24) {
    return txTax(msg.sender);
  }

  /// @notice Tax applied per transfer
  /// @param from Sender address
  function txTax(address from) public view returns (uint24) {
    unchecked {
      return from == address(this) || from == _dex.pair ? 0 : _totalTxTax;
    }
  }

  /// @notice Tax applied for buying
  /// @dev Taking in consideration your wallet address
  function buyTax() external view returns (uint24) {
    return buyTax(msg.sender);
  }

  /// @notice Tax applied for buying
  /// @param from Buyer's address
  function buyTax(address from) public view returns (uint24) {
    if (_suspendTaxes) { return 0; }

    unchecked {
      return from == address(this) || from == _dex.pair ? 0 : _totalBuyTax;
    }
  }
  /// @notice Tax applied for selling
  /// @dev Taking in consideration your wallet address
  function sellTax() external view returns (uint24) {
    return sellTax(msg.sender);
  }

  /// @notice Tax applied for selling
  /// @param to Seller's address
  function sellTax(address to) public view returns (uint24) {
    if (_suspendTaxes) { return 0; }

    unchecked {
      return to == address(this) || to == _owner || to == _dex.pair || to == _dex.router ? 0 : _totalSellTax;
    }
  }

  /// @notice List of all tax beneficiaries and their assigned percentage, according to type of transfer
  /// @custom:return `list[].account` Beneficiary address
  /// @custom:return `list[].percent[3]` Index 0 is for tx tax, 1 is for buy tax, 2 is for sell tax, multiplied by denominator
  function listTaxBeneficiaries() external view returns (taxBeneficiaryView[] memory list) {
    list = new taxBeneficiaryView[](5);

    unchecked {
      for (uint8 i; i < 5; i++) { list[i] = taxBeneficiaryView(_taxBeneficiary[i].account, _taxBeneficiary[i].percent, _taxBeneficiary[i].unclaimed); }
    }
  }

  /// @notice Sets a tax beneficiary
  /// @dev Maximum of 5 wallets can be assigned
  /// @param slot Slot number (0 to 4)
  /// @param account Beneficiary address
  /// @param percent[3] Index 0 is for tx tax, 1 is for buy tax, 2 is for sell tax, multiplied by denominator
  function setTaxBeneficiary(uint8 slot, address account, uint24[3] memory percent) external onlyOwner {
    require(!_renounced.Taxable);

    _setTaxBeneficiary(slot, account, percent);
  }

  function _setTaxBeneficiary(uint8 slot, address account, uint24[3] memory percent) internal {
    require(slot < 5);
    require(account != address(this) && account != address(0xdEaD) && account != address(0));

    taxBeneficiary storage _taxBeneficiary = _taxBeneficiary[slot];

    unchecked {
      _totalTxTax += percent[0] - _taxBeneficiary.percent[0];
      _totalBuyTax += percent[1] - _taxBeneficiary.percent[1];
      _totalSellTax += percent[2] - _taxBeneficiary.percent[2];

      require(_totalTxTax <= 25 * _denominator && ((_totalBuyTax <= 25 * _denominator && _totalSellTax <= 25 * _denominator) && (_totalBuyTax + _totalSellTax <= 25 * _denominator)), "High Tax");
    }

    _taxBeneficiary.account = account;
    _taxBeneficiary.percent = percent;

    if (!_taxBeneficiary.exists) { _taxBeneficiary.exists = true; }

    emit SetTaxBeneficiary(slot, account, percent);
  }

  /// @notice Triggers the tax distribution
  /// @dev Will only be executed if there is no ongoing tax distribution and the min. threshold has been reached unless forced
  /// @param force Ignore the min. threshold amount
  function autoTaxDistribute(bool force) external onlyOwner {
    require(!_swapping && !_distributing);

    _autoTaxDistribute(force);
  }

  function _autoTaxDistribute(bool force) internal lockDistributing {
    if (!force) {
      if (_amountForTaxDistribution == 0 || _balance[address(this)] < _amountForTaxDistribution || _amountForTaxDistribution < _minTaxDistributionAmount) { return; }
    }

    unchecked {
      uint256 distributed;

      for (uint8 i; i < 5; i++) {
        address account = _taxBeneficiary[i].account;
        uint256 unclaimed = _taxBeneficiary[i].unclaimed;

        if (unclaimed == 0 || account == _dex.pair) { continue; }

        uint256 _distributed = _distribute(account, unclaimed);

        if (_distributed > 0) { _taxBeneficiary[i].unclaimed -= _distributed; }

        distributed += _distributed;
      }

      _lastTaxDistribution = _timestamp();

      emit TaxDistributed(distributed);
    }
  }

  function _distribute(address account, uint256 unclaimed) private returns (uint256) {
    super._transfer(address(this), account, unclaimed);

    _amountForTaxDistribution -= unclaimed;

    return unclaimed;
  }

  /// @notice Suspend or reinstate tax collection
  /// @param status True to suspend, False to reinstate existent taxes
  function suspendTaxes(bool status) external onlyOwner {
    require(!_renounced.Taxable);

    _suspendTaxes = status;
  }

  /// @notice Checks if tax collection is currently suspended
  function taxesSuspended() external view returns (bool) {
    return _suspendTaxes;
  }

  /// @notice Returns the minimum percentage of the total supply accumulated in the Smart-Contract balance to trigger tax distribution
  function getMinTaxDistributionPercent() external view returns (uint24) {
    return _minTaxDistributionPercent;
  }

  /// @notice Sets the minimum percentage of the total supply accumulated in the Smart-Contract balance to trigger tax distribution
  /// @param percent Desired percentage, multiplied by denominator (0.001% to 1% of total supply)
  function setMinTaxDistributionPercent(uint24 percent) external onlyOwner {
    require(!_renounced.Taxable);
    require(percent >= 1 && percent <= 1000, "0.001% to 1%");

    _setMinTaxDistributionPercent(percent);
  }

  function _setMinTaxDistributionPercent(uint24 percent) internal {
    _minTaxDistributionPercent = percent;
    _minTaxDistributionAmount = _percentage(_totalSupply, uint256(percent));
  }
}

// File: CF_DEXRouterV2.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.23;

import "./CF_Ownable.sol";
import "./CF_Common.sol";
import "./CF_ERC20.sol";

abstract contract CF_DEXRouterV2 is CF_Ownable, CF_Common, CF_ERC20 {
  event SwapAndLiquify(uint256 tokenAmount, uint256 ethAmount, uint256 liquidity);
  event SwappedTokensForETH(uint256 tokenAmount, uint256 ethAmount);
  event SwappedTokensForERC20(address token, uint256 token0Amount, uint256 token1Amount);
  event SetDEXRouter(address indexed router, address indexed pair, address receiver);
  event RenouncedDEXRouterV2();

  modifier lockSwapping {
    _swapping = true;
    _;
    _swapping = false;
  }

  /// @notice Permanently renounce and prevent the owner from being able to update the DEX features
  /// @dev Existing settings will continue to be effective
  function renounceDEXRouterV2() external onlyOwner {
    _renounced.DEXRouterV2 = true;

    emit RenouncedDEXRouterV2();
  }

  /// @notice Sets the DEX router and where to receive the LP tokens
  /// @param router Address of the DEX router
  /// @param receiver Address of the LP tokens receiver
  function setDEXRouter(address router, address receiver) external onlyOwner returns (address) {
    require(!_renounced.DEXRouterV2);

    return _setDEXRouter(router, receiver);
  }

  function _setDEXRouter(address router, address receiver) internal returns (address) {
    require(router != address(0));

    if (_dex.router != router) {
      IDEXRouterV2 _router = IDEXRouterV2(router);
      IDEXFactoryV2 factory = IDEXFactoryV2(_router.factory());
      address WETH = _router.WETH();
      address pair = factory.getPair(address(this), WETH);

      if (pair == address(0)) { pair = factory.createPair(address(this), WETH); }

      _dex = DEXRouterV2(router, pair, WETH, receiver);
    }

    if (receiver != _dex.receiver) { _dex.receiver = receiver; }

    emit SetDEXRouter(router, _dex.pair, receiver);

    return _dex.pair;
  }

  /// @notice Returns the DEX router currently in use
  function getDEXRouter() external view returns (address) {
    return _dex.router;
  }

  /// @notice Returns the trading pair
  function getDEXPair() external view returns (address) {
    return _dex.pair;
  }

  /// @notice Returns address of the LP tokens receiver
  function getDEXReceiver() external view returns (address) {
    return _dex.receiver;
  }

  /// @notice Checks the status of the auto-swapping feature
  function isSwapEnabled() external view returns (bool) {
    return _swapEnabled;
  }

  /// @notice Checks whether the token can be traded through the assigned DEX
  function isTradingEnabled() external view returns (bool) {
    return _tradingEnabled > 0;
  }

  /// @notice Assign the excess token balance of the Smart-Contract to liquidity
  function liquifyExcess() external onlyOwner {
    require(_swapEnabled && !_swapping);

    unchecked {
      uint256 assigned = _amountForTaxDistribution + _amountForLiquidity;

      require(_balance[address(this)] > assigned);

      uint256 excess = _balance[address(this)] - assigned;

      _amountForLiquidity += excess;
    }

    _autoSwap(false);
  }

  /// @notice Swaps the assigned amount for liquidity and taxes to the corresponding token
  /// @dev Will only be executed if there is no ongoing swap or tax distribution and the min. threshold has been reached unless forced
  /// @param force Ignore the min. threshold amount
  function autoSwap(bool force) external onlyOwner {
    require(_swapEnabled && !_swapping);

    _autoSwap(force);
  }

  function _autoSwap(bool force) internal lockSwapping {
    if (!_swapEnabled) { return; }

    unchecked {
      if (force || (_amountForLiquidity / 2 >= _minSwapAmount && _balance[address(this)] >= _amountForLiquidity)) {
        uint256 tokenAmountForLiquidity = _amountForLiquidity / 2;
        uint256 ethBalance = address(this).balance;
        address[] memory pathToSwapExactTokensForETH = new address[](2);
        pathToSwapExactTokensForETH[0] = address(this);
        pathToSwapExactTokensForETH[1] = _dex.WETH;

        _approve(address(this), _dex.router, tokenAmountForLiquidity);

        try IDEXRouterV2(_dex.router).swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmountForLiquidity, 0, pathToSwapExactTokensForETH, address(this), block.timestamp + 1) {
          _lastSwap = _timestamp();

          if (_amountForLiquidity > 0) { _amountForLiquidity /= 2; }

          uint256 ethAmount = address(this).balance - ethBalance;

          emit SwappedTokensForETH(tokenAmountForLiquidity, ethAmount);

          if (ethAmount > 0) {
            if (tokenAmountForLiquidity > 0 && ethAmount > 0) {
              _approve(address(this), _dex.router, tokenAmountForLiquidity);

              try IDEXRouterV2(_dex.router).addLiquidityETH{ value: ethAmount }(address(this), tokenAmountForLiquidity, 0, 0, _dex.receiver, block.timestamp + 1) returns (uint256 amountToken, uint256 amountETH, uint256 liquidity) {
                emit SwapAndLiquify(amountToken, amountETH, liquidity);

                _amountForLiquidity = 0;
              } catch {
                _approve(address(this), _dex.router, 0);
              }
            }
          }
        } catch {
          _approve(address(this), _dex.router, 0);
        }
      }
    }
  }

  /// @notice Returns the minimum percentage of the total supply in the Smart-Contract balance to trigger auto swap
  function getMinSwapPercent() external view returns (uint24) {
    return _minSwapPercent;
  }

  /// @notice Sets the minimum percentage of the total supply in the Smart-Contract balance to trigger auto swap
  /// @param percent Desired percentage, multiplied by denominator (0.001% to 1% of total supply)
  function setMinSwapPercent(uint24 percent) external onlyOwner {
    require(!_renounced.DEXRouterV2);
    require(percent >= 1 && percent <= 1000, "0.001% to 1%");

    _setMinSwapPercent(percent);
  }

  function _setMinSwapPercent(uint24 percent) internal {
    _minSwapPercent = percent;
    _minSwapAmount = _percentage(_totalSupply, uint256(percent));
  }

  /// @notice Enables or disables the auto swap function
  /// @param status True to enable, False to disable
  function setSwapStatus(bool status) external onlyOwner {
    require(!_renounced.DEXRouterV2);
    require(!status || _dex.router != address(0), "No DEX");

    _swapEnabled = status;
  }

  /// @notice Enables the trading capability via the DEX set up
  /// @dev Once enabled, it cannot be reverted unless using the pause method
  function enableTrading() external onlyOwner {
    require(!_renounced.DEXRouterV2);
    require(_tradingEnabled == 0, "Already enabled");

    _tradingEnabled = _timestamp();
  }
}

// File: CF_HolderList.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.23;

import "./CF_Common.sol";

abstract contract CF_HolderList is CF_Common {
  struct Holder {
    address account;
    uint256 balance;
  }

  /// @notice Total number of holders
  function totalHolders() public view returns (uint256 total) {
    unchecked {
      uint256 cnt = _holders.length;

      for (uint256 i; i < cnt; i++) {
        address account = _holders[i];

        if (account == address(0) || _balance[account] == 0) { continue; }

        ++total;
      }
    }
  }

  /// @notice Retrieves a list of wallets and their balance, paginated
  /// @param offset How many rows to skip over
  /// @param limit How many rows to return, at most
  /// @return holders Rows matching your criteria
  /// @return total Total number of holders
  function getHolders(uint256 offset, uint256 limit) public view returns (Holder[] memory, uint256 total) {
    total = totalHolders();

    require(limit >= offset && offset <= total, "Invalid range");

    unchecked {
      uint256 rows = (limit - offset) + 1;

      if (rows > total - offset) { rows = total - offset; }

      require(rows > 0, "Out of range");

      Holder[] memory holders = new Holder[](rows);

      uint256 cnt = _holders.length;
      uint256 s;
      uint256 h;

      for (uint256 i; i < cnt; i++) {
        address account = _holders[i];

        if (account == address(0) || _balance[account] == 0) { continue; }
        if (s++ < offset) { continue; }

        holders[h] = Holder(account, _balance[account]);

        if (++h >= rows) { break; }
      }

      return (holders, total);
    }
  }

  /// @notice Retrieves the full list of wallets and their balance
  /// @dev Use the paginated version of this function if the output exceeds the return limit
  function getHolders() external view returns (Holder[] memory, uint256 total) {
    total = totalHolders();

    return getHolders(0, total);
  }
}

// File: IDEXV2.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.23;

interface IDEXRouterV2 {
  function factory() external pure returns (address);
  function WETH() external pure 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 swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external;
  function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external;
}

interface IDEXFactoryV2 {
  function createPair(address tokenA, address tokenB) external returns (address pair);
  function getPair(address tokenA, address tokenB) external returns (address pair);
}