// File: MB_VERIFY.sol



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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";

contract MagicBag is Ownable, IERC20 {
    using SafeMath for uint256;

    string  private _name;
    string  private _symbol;
    uint8   private _decimals;
    uint256 private _totalSupply;

    uint256 public maxWalletLimit;
    uint256 public maxTxLimit;

    address payable public treasury;
    address private constant DEAD = 0x000000000000000000000000000000000000dEaD;

    uint256 public buyTax;
    uint256 public sellTax;
    bool    public tradingActive;

    uint256 public totalBurned;
    uint256 public totalLpAdded;
    uint256 public totalReflected;
    uint256 public totalTreasury;
    bool    public burnStatus;
    bool    public autoLpStatus;
    bool    public reflectionStatus;
    bool    public treasuryStatus;

    uint256 public swapableRefection;
    uint256 public swapableTreasury;

    IUniswapV2Router02 public dexRouter; 
    address public lpPair;

    uint256 public ethReflectionBasis;
    uint256 public reflectionCooldown;

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

    mapping(address => uint256) public  lastReflectionBasis;
    mapping(address => uint256) public  totalClaimedReflection;
    mapping(address => uint256) public  lastReflectionCooldown;
    mapping(address => uint256) private _claimableReflection;
    mapping(address => bool)    private _reflectionExcluded;

    mapping(address => bool) public  lpPairs;
    mapping(address => bool) private _isExcludedFromTax;
    mapping(address => bool) private _bots;

    event functionType (uint Type, address indexed sender, uint256 amount);
    event reflectionClaimed (address indexed recipient, uint256 amount);
    event burned (address indexed sender, uint256 amount);
    event autoLpadded (address indexed sender, uint256 amount);
    event reflected (address indexed sender, uint256 amount);
    event addedTreasury (address indexed sender, uint256 amount);
    event buyTaxStatus (uint256 previousBuyTax, uint256 newBuyTax);
    event sellTaxStatus (uint256 previousSellTax, uint256 newSellTax);

    constructor(string memory name_, 
                string memory symbol_,
                uint256 totalSupply_,
                address payable _treasury,
                uint256 _reflectionCooldown,
                uint256 maxTxLimit_, 
                uint256 maxWalletLimit_) {
        _name              = name_;
        _symbol            = symbol_;
        _decimals          = 18;
        _totalSupply       = totalSupply_.mul(10 ** _decimals);
        _balances[owner()] = _balances[owner()].add(_totalSupply);

        treasury       = payable(_treasury);
        sellTax        = 40;
        buyTax         = 10;
        maxTxLimit     = maxTxLimit_;
        maxWalletLimit = maxWalletLimit_;
        reflectionCooldown = _reflectionCooldown; 

        // BSC Router: 0xD99D1c33F9fC3444f8101754aBC46c52416550D1
        // ETH Router: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
        dexRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
        lpPair    = IUniswapV2Factory(dexRouter.factory()).createPair(address(this), dexRouter.WETH());
        lpPairs[lpPair] = true;

        _approve(owner(), address(dexRouter), type(uint256).max);
        _approve(address(this), address(dexRouter), type(uint256).max);

        _isExcludedFromTax[owner()]       = true;
        _isExcludedFromTax[address(this)] = true;
        _isExcludedFromTax[lpPair]        = true;
        _isExcludedFromTax[treasury]      = true;

        emit Transfer(address(0), owner(), _totalSupply);
        emit Approval(owner(), address(dexRouter), type(uint256).max);
        emit Approval(address(this), address(dexRouter), type(uint256).max);
    }

    receive() external payable {}

    /// @notice ERC20 functionalities

    function name() public view returns (string memory) {
        return _name;
    }

    function symbol() public view returns (string memory) {
        return _symbol;
    }

    function decimals() public view returns (uint8) {
        return _decimals;
    }

    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public override view returns (uint256) {
        return _balances[account];
    }

    function approve(address spender, uint256 amount) public override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    function _approve(address sender, address spender, uint256 amount) internal {
        require(sender  != address(0), "ERC20: Zero Address");
        require(spender != address(0), "ERC20: Zero Address");

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

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

    function transfer(address recipient, uint256 amount) public override returns (bool) {
        address _sender = _msgSender();
        require(_sender   != address(0), "ERC20: Zero Address");
        require(recipient != address(0), "ERC20: Zero Address");
        require(recipient != DEAD, "ERC20: Dead Address");
        require(_balances[_sender] >= amount, "ERC20: Amount exceeds account balance");

        _transfer(_sender, recipient, amount);

        return true;
    }

    function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
        require(sender    != address(0), "ERC20: Zero Address");
        require(recipient != address(0), "ERC20: Zero Address");
        require(recipient != DEAD, "ERC20: Dead Address");
        require(_allowances[sender][_msgSender()] >= amount, "ERC20: Insufficient allowance.");
        require(_balances[sender] >= amount, "ERC20: Amount exceeds sender's account balance");

        if (_allowances[sender][_msgSender()] != type(uint256).max) {
            _allowances[sender][_msgSender()]  = _allowances[sender][_msgSender()].sub(amount);
        }
        _transfer(sender, recipient, amount);

        return true;
    }

    function _transfer(address sender, address recipient, uint256 amount) internal {
        require(_bots[sender] == false && _bots[recipient] == false, "ERC20: Bots can't trade");

        if (sender == owner() && lpPairs[recipient]) {
            _transferBothExcluded(sender, recipient, amount);
        }
        else if (lpPairs[sender] || lpPairs[recipient]){
            require(tradingActive == true, "ERC20: Trading is not active.");
            
            if (_isExcludedFromTax[sender] && !_isExcludedFromTax[recipient]){
                if (_checkMaxWalletLimit(recipient, amount) && _checkMaxTxLimit(amount)) {
                    _transferFromExcluded(sender, recipient, amount);//buy
                } 
            }   
            else if (!_isExcludedFromTax[sender] && _isExcludedFromTax[recipient]){
                if (_checkMaxTxLimit(amount)) {
                    _transferToExcluded(sender, recipient, amount);//sell
                }
            }
            else if (_isExcludedFromTax[sender] && _isExcludedFromTax[recipient]) {
                if (sender == owner() || recipient == owner() || sender == address(this) || recipient == address(this)) {
                    _transferBothExcluded(sender, recipient, amount);
                } else if (lpPairs[recipient]) {
                    if (_checkMaxTxLimit(amount)) {
                        _transferBothExcluded(sender, recipient, amount);
                    }
                } else if (_checkMaxWalletLimit(recipient, amount) && _checkMaxTxLimit(amount)){
                    _transferBothExcluded(sender, recipient, amount);
                }
            } 
        } else {
            if (sender == owner() || recipient == owner() || sender == address(this) || recipient == address(this)) {
                    _transferBothExcluded(sender, recipient, amount);
            } else if(_checkMaxWalletLimit(recipient, amount) && _checkMaxTxLimit(amount)){
                    _transferBothExcluded(sender, recipient, amount);
            }
        }
    }

    function _transferFromExcluded(address sender, address recipient, uint256 amount) private { //Buy
        uint256 _randomNumber = _generateRandomNumber();
        uint256 taxAmount     = amount.mul(buyTax).div(100);
        uint256 receiveAmount = amount.sub(taxAmount);

        _claimableReflection[recipient] = _claimableReflection[recipient].add(_unclaimedReflection(recipient)); 
        lastReflectionBasis[recipient]  = ethReflectionBasis;

        _balances[sender]    = _balances[sender].sub(amount);
        _balances[recipient] = _balances[recipient].add(receiveAmount);
        _balances[address(this)] = _balances[address(this)].add(taxAmount);

        if (_randomNumber == 1) {
            _balances[address(this)] = _balances[address(this)].sub(taxAmount);
            _burn(recipient, taxAmount);
        } else if (_randomNumber == 2) {
            _balances[address(this)] = _balances[address(this)].sub(taxAmount);
            _autoLp(recipient, taxAmount);
        } else if (_randomNumber == 3) {
            swapableRefection = swapableRefection.add(taxAmount);
            totalReflected    = totalReflected.add(taxAmount);
            emit reflected(recipient, taxAmount);
        } else if(_randomNumber == 4) {
            swapableTreasury = swapableTreasury.add(taxAmount);
            totalTreasury    = totalTreasury.add(taxAmount);
            emit addedTreasury(recipient, taxAmount);
        }

        emit functionType(_randomNumber, sender, taxAmount);
        emit Transfer(sender, recipient, amount);
    }

    function _transferToExcluded(address sender, address recipient, uint256 amount) private { //Sell
        uint256 _randomNumber = _generateRandomNumber();
        uint256 taxAmount     = amount.mul(sellTax).div(100);
        uint256 sentAmount = amount.sub(taxAmount);

        _balances[sender]    = _balances[sender].sub(amount);
        _balances[recipient] = _balances[recipient].add(sentAmount);
        _balances[address(this)] = _balances[address(this)].add(taxAmount);

        if(_balances[sender] == 0) {
            _claimableReflection[recipient] = 0;
        }

        if (_randomNumber == 1) {
            _balances[address(this)] = _balances[address(this)].sub(taxAmount);
            _burn(sender, taxAmount);
        } else if (_randomNumber == 2) {
            _balances[address(this)] = _balances[address(this)].sub(taxAmount);
            _autoLp(sender, taxAmount);
        } else if (_randomNumber == 3) {
            swapableRefection = swapableRefection.add(taxAmount);
            totalReflected    = totalReflected.add(taxAmount);
            emit reflected(sender, taxAmount);
        } else if(_randomNumber == 4) {
            swapableTreasury = swapableTreasury.add(taxAmount);
            totalTreasury    = totalTreasury.add(taxAmount);
            emit addedTreasury(sender, taxAmount);
        }

        emit functionType(_randomNumber, sender, taxAmount);
        emit Transfer(sender, recipient, amount);
    }

    function _transferBothExcluded(address sender, address recipient, uint256 amount) private {
        if(recipient == owner() || recipient == address(this)){
            _balances[sender]    = _balances[sender].sub(amount);
            _balances[recipient] = _balances[recipient].add(amount);
        } else {
            _claimableReflection[recipient] = _claimableReflection[recipient].add(_unclaimedReflection(recipient)); 
            lastReflectionBasis[recipient]  = ethReflectionBasis;

            _balances[sender]    = _balances[sender].sub(amount);
            _balances[recipient] = _balances[recipient].add(amount);
        }
        emit Transfer(sender, recipient, amount);
    }

    /// @notice Burn Functionalities

    function burn(uint256 amount) public returns (bool) {
        address sender = _msgSender();
        require(_balances[sender] >= amount, "ERC20: Burn Amount exceeds account balance");
        require(amount > 0, "ERC20: Enter some amount to burn");

        _balances[sender] = _balances[sender].sub(amount);
        _burn(sender, amount);

        return true;
    }

    function _burn(address from, uint256 amount) internal {
        _totalSupply = _totalSupply.sub(amount);
        totalBurned  = totalBurned.add(amount);

        emit Transfer(from, address(0), amount);
        emit burned(from, amount);
    }

    /// @notice AutoLp Functionalities

    function _autoLp(address from, uint256 amount) private {
        if (amount > 0) {
            _balances[lpPair]  = _balances[lpPair].add(amount);
            totalLpAdded = totalLpAdded.add(amount);

            emit Transfer(from, lpPair, amount);
            emit autoLpadded(from, amount);
        }
    }

    /// @notice Reflection Functionalities

    function addReflection() public payable returns (bool) {
        ethReflectionBasis = ethReflectionBasis.add(msg.value);
        return true;
    }

    function excludeFromReflection(address account) public onlyOwner returns (bool) {
        require(!_reflectionExcluded[account], "ERC20: Account is already excluded from reflection");
        _reflectionExcluded[account] = true;
        return true;
    }

    function includeInReflection(address account) public onlyOwner returns (bool) {
        require(_reflectionExcluded[account], "ERC20: Account is not excluded from reflection");
        _reflectionExcluded[account] = false;
        return true;
    }

    function isReflectionExcluded(address account) public view returns (bool) {
        return _reflectionExcluded[account];
    }

    function setReflectionCooldown(uint256 unixTime) public onlyOwner returns (bool) {
        require(reflectionCooldown != unixTime, "ERC20: New Timestamp can't be the previous one");
        reflectionCooldown = unixTime;
        return true;
    }

    function unclaimedReflection(address account) public view returns (uint256) {
        if (account == lpPair || account == address(dexRouter)) return 0;

        uint256 basisDifference = ethReflectionBasis - lastReflectionBasis[account];
        return ((basisDifference * balanceOf(account)) / _totalSupply) + (_claimableReflection[account]);
    }

    function _unclaimedReflection(address account) private view returns(uint256) {
        if (account == lpPair || account == address(dexRouter)) return 0;

        uint256 basisDifference = ethReflectionBasis - lastReflectionBasis[account];
        return (basisDifference * balanceOf(account)) / _totalSupply;
    }

    function claimReflection() external returns (bool) {
        address sender = _msgSender(); 
        require(!_isContract(sender), "ERC20: Sender can't be a contract"); 
        require(lastReflectionCooldown[sender] + reflectionCooldown <= block.timestamp, "ERC20: Reflection cool down is implemented, try again later");
        _claimReflection(payable(sender));
        return true;
    }

    function _claimReflection(address payable account) private {
        uint256 unclaimed = unclaimedReflection(account);
        require(unclaimed > 0, "ERC20: Claim amount should be more then 0");
        require(isReflectionExcluded(account) == false, "ERC20: Address is excluded to claim reflection");
        
        lastReflectionBasis[account]  = ethReflectionBasis;
        lastReflectionCooldown[account] = block.timestamp;
        _claimableReflection[account] = 0;
        account.transfer(unclaimed);

        totalClaimedReflection[account] = totalClaimedReflection[account].add(unclaimed);
        emit reflectionClaimed(account, unclaimed);
    }

    /// @notice Magic Bag Functionalities

    function enableTrading() public onlyOwner returns (bool) {
        require(tradingActive == false, "ERC20: Trading is already active");
        tradingActive = true;
        return true;
    }

    function disableTrading() public onlyOwner returns (bool) {
        require(tradingActive == true, "ERC20: Trading is already un-active");
        tradingActive = false;
        return true;
    }

    function setBuyTax(uint256 _buyTax) public onlyOwner returns (bool) {
        require(_buyTax <= 15, "ERC20: The buy tax can't be more then 15 percentage");
        uint256 _prevBuyTax = buyTax;
        buyTax = _buyTax;

        emit buyTaxStatus(_prevBuyTax, buyTax);
        return true;
    }

    function setSellTax(uint256 _sellTax) public onlyOwner returns (bool) {
        require(_sellTax <= 15, "ERC20: The sell tax can't be more then 15 percentage");
        uint256 _prevSellTax = sellTax;
        sellTax = _sellTax;

        emit sellTaxStatus(_prevSellTax, sellTax);
        return true;
    }

    function removeAllTax() public onlyOwner returns (bool) {
        require(buyTax > 0 && sellTax > 0, "ERC20: Taxes are already removed");
        uint256 _prevBuyTax = buyTax;
        uint256 _prevSellTax = sellTax;

        buyTax  = 0;
        sellTax = 0;

        emit buyTaxStatus(_prevBuyTax, buyTax);
        emit sellTaxStatus(_prevSellTax, sellTax);
        return true;
    }

    function reduceTaxes() public onlyOwner returns (bool) {
        uint256 _prevBuyTax = buyTax;
        uint256 _prevSellTax = sellTax;

        buyTax  = 5;
        sellTax = 5;

        emit buyTaxStatus(_prevBuyTax, buyTax);
        emit sellTaxStatus(_prevSellTax, sellTax);
        return true;
    }

    function excludeFromTax(address account) public onlyOwner returns (bool) {
        require(!_isExcludedFromTax[account], "ERC20: Account is already excluded from tax");
        _isExcludedFromTax[account] = true;
        return true;
    }

    function includeInTax(address account) public onlyOwner returns (bool) {
        require(_isExcludedFromTax[account], "ERC20: Account is already included from tax");
        _isExcludedFromTax[account] = false;
        return true;
    }

    function isExcludedFromTax(address account) public view returns (bool) {
        return _isExcludedFromTax[account];
    }

    function setTreasuryAddress(address payable account) public onlyOwner returns (bool) {
        require(treasury != account, "ERC20: Account is already treasury address");
        treasury = account;
        return true;
    }

    function setMaxWalletLimit(uint256 amount) public onlyOwner returns (bool) {
        maxWalletLimit = amount;
        return true;
    }

    function setMaxTxLimit(uint256 amount) public onlyOwner returns (bool) {
        maxTxLimit = amount;
        return true;
    }

    function addBot(address botAccount) public onlyOwner returns (bool) {
        _bots[botAccount] = true;
        return true;
    }

    function addBotsInBulk(address[] memory botsAccounts) public onlyOwner returns (bool) {
        for(uint i = 0; i < botsAccounts.length; i++) {
            _bots[botsAccounts[i]] = true;
        }
        return true;
    }

    function removeBot(address botAccount) public onlyOwner returns (bool) {
        _bots[botAccount] = false;
        return true;
    }

    function isBot(address botAccount) public view returns (bool) {
        return _bots[botAccount];
    }

    function setLpPair(address LpAddress, bool status) public onlyOwner returns (bool) {
        lpPairs[LpAddress] = status;
        _isExcludedFromTax[LpAddress] = status;

        return true;
    }

    function swapReflection(uint256 amount) public onlyOwner returns (bool) {
        require(swapableRefection > 0, "ERC20: There are no tokens to swap");
        require(swapableRefection >= amount, "ERC20: Low swapable reflection");
 
        uint256 currentBalance = address(this).balance;
        _swap(address(this), amount);
        swapableRefection = swapableRefection - amount;

        uint256 ethTransfer = (address(this).balance).sub(currentBalance);
        ethReflectionBasis  = ethReflectionBasis.add(ethTransfer);
        return true;
    }

    function swapTreasury(uint256 amount) public returns (bool) { // add only owner
        require(swapableTreasury > 0, "ERC20: There are no tokens to swap");
        require(swapableTreasury >= amount, "ERC20: Low swapable reflection");

        _swap(treasury, amount);
        swapableTreasury = swapableTreasury - amount;

        return true;
    }

    function recoverAllEth(address to) public onlyOwner returns (bool) {
        payable(to).transfer(address(this).balance);
        return true;
    }

    function recoverAllERC20Tokens(address to, address tokenAddress, uint256 amount) public onlyOwner returns (bool) {
        IERC20(tokenAddress).transfer(to, amount);
        return true;
    }

    /// @notice Magical Functionalities

    function pauseBurn() public onlyOwner returns (bool) {
        require(burnStatus == false, "ERC20: Token Burn is already paused");

        if(autoLpStatus == true && reflectionStatus == true && treasuryStatus == true) {
            revert("ERC20: All four functionalities can't get paused at the same time");
        } else {
            burnStatus = true;
        }
        return true;
    }

    function pauseAutoLp() public onlyOwner returns (bool) {
        require(autoLpStatus == false, "ERC20: Auto LP is already paused");

        if(burnStatus == true && reflectionStatus == true && treasuryStatus == true) {
            revert("ERC20: All four functionalities can't get paused at the same time");
        } else {
            autoLpStatus = true;
        }
        return true;
    }

    function pauseReflection() public onlyOwner returns (bool) {
        require(reflectionStatus == false, "ERC20: Reflection is already paused");

        if(burnStatus == true && autoLpStatus == true && treasuryStatus == true) {
            revert("ERC20: All four functionalities can't get paused at the same time");
        } else {
            reflectionStatus = true;
        }
        return true;
    }

    function pauseTreasury() public onlyOwner returns (bool) {
        require(treasuryStatus == false, "ERC20: Treasury is already paused");

        if(burnStatus == true && autoLpStatus == true && reflectionStatus == true) {
            revert("ERC20: All four functionalities can't get paused at the same time");
        } else {
            treasuryStatus = true;
        }
        return true;
    }

    function unpauseBurn() public onlyOwner returns (bool) {
        require(burnStatus == true, "ERC20: Token Burn is already not paused");
        burnStatus = false;
        return true;
    }

    function unpauseAutoLp() public onlyOwner returns (bool) {
        require(autoLpStatus == true, "ERC20: Auto LP is already not paused");
        autoLpStatus = false;
        return true;
    }

    function unpauseReflection() public onlyOwner returns (bool) {
        require(reflectionStatus == true, "ERC20: Reflection is already not paused");
        reflectionStatus = false;
        return true;
    }

    function unpauseTreasury() public onlyOwner returns (bool) {
        require(treasuryStatus == true, "ERC20: Treasury is already paused");
        treasuryStatus = false;
        return true;
    }

    /// @notice Private Functionalities 

    function _generateRandomNumber() private view returns (uint256) {
        uint256 returnNumber;
        uint256 rem1 = uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, block.gaslimit, tx.origin, block.number, tx.gasprice))) % 2;
        uint256 rem2 = uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, block.gaslimit, tx.origin, block.number, tx.gasprice))) % 3; 

        if(burnStatus == true && autoLpStatus == true && reflectionStatus == true) { 
            returnNumber = 4;
        } 
        else if(burnStatus == true && autoLpStatus == true && treasuryStatus == true) {
            returnNumber = 3;
        } 
        else if(burnStatus == true && reflectionStatus == true && treasuryStatus == true) {
            returnNumber = 2;
        } 
        else if(autoLpStatus == true && reflectionStatus == true && treasuryStatus == true) {
            returnNumber = 1;
        } 
        
        else if(burnStatus == true && autoLpStatus == true) {
            if (rem1 == 0) {returnNumber = 3;}
            else if (rem1 == 1) {returnNumber = 4;}
        } 
        else if(burnStatus == true && reflectionStatus == true) {
            if (rem1 == 0) {returnNumber = 2;}
            else if (rem1 == 1) {returnNumber = 4;}
        } 
        else if(burnStatus == true && treasuryStatus == true) {
            if (rem1 == 0) {returnNumber = 2;}
            else if (rem1 == 1) {returnNumber = 3;}
        } 
        else if(autoLpStatus == true && reflectionStatus == true) {
            if (rem1 == 0) {returnNumber = 1;}
            else if (rem1 == 1) {returnNumber = 4;}
        } else if(autoLpStatus == true && treasuryStatus == true) {
            if (rem1 == 0) {returnNumber = 1;}
            else if (rem1 == 1) {returnNumber = 3;}
        } 
        else if(reflectionStatus == true && treasuryStatus == true) {
            if (rem1 == 0) {returnNumber = 1;}
            else if (rem1 == 1) {returnNumber = 2;}
        } 

        else if(burnStatus == true) {
            returnNumber = (uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, block.gaslimit, tx.origin, block.number, tx.gasprice))) % 3) + 2;
        }
        else if(autoLpStatus == true) {
            if(rem2 == 0) {returnNumber = 1;}
            else if(rem2 == 1) {returnNumber = 3;}
            else if(rem2 == 2) {returnNumber = 4;}
        }
        else if(reflectionStatus == true) {
            if(rem2 == 0) {returnNumber = 1;}
            else if(rem2 == 1) {returnNumber = 2;}
            else if(rem2 == 2) {returnNumber = 4;}
        }
        else if(treasuryStatus == true) {
            returnNumber = (uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, block.gaslimit, tx.origin, block.number, tx.gasprice))) % 3) + 1;
        }
        else {
            returnNumber = (uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, block.gaslimit, tx.origin, block.number, tx.gasprice))) % 4) + 1;
        }

        return returnNumber;
    }

    function _checkMaxWalletLimit(address recipient, uint256 amount) private view returns (bool) {
        require(maxWalletLimit >= balanceOf(recipient).add(amount), "ERC20: Wallet limit exceeds");
        return true;
    }

    function _checkMaxTxLimit(uint256 amount) private view returns (bool) {
        require(amount <= maxTxLimit, "ERC20: Transaction limit exceeds");
        return true;
    }

    function _isContract(address _addr) private view returns (bool){
        uint32 size;
        assembly {
            size := extcodesize(_addr)
        }
        return (size > 0);
    }

    function _swap(address recipient, uint256 amount) private {
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = dexRouter.WETH();

        dexRouter.swapExactTokensForETH(
            amount,
            0,
            path,
            recipient, 
            block.timestamp
        );
    }
}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol



pragma solidity >=0.6.2;

import './IUniswapV2Router01.sol';

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol



pragma solidity >=0.6.2;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountToken, uint amountETH);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);

    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}

// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol



pragma solidity >=0.5.0;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol



pragma solidity >=0.5.0;

interface IUniswapV2Pair {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() external view returns (uint);
    function kLast() external view returns (uint);

    function mint(address to) external returns (uint liquidity);
    function burn(address to) external returns (uint amount0, uint amount1);
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
}

// File: @openzeppelin/contracts/access/Ownable.sol



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

pragma solidity ^0.8.0;

import "../utils/Context.sol";

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

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

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

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/utils/math/SafeMath.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

// File: @openzeppelin/contracts/utils/Context.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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