contract AlphaCoin is Context, IERC20, Ownable {
    using Address for address;

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

    mapping (address => bool) private _isExcludedFromFee;

    mapping (address => bool) private _isExcluded;
    address[] private _excluded;
    mapping (address => bool) private _isBlackListedBot;
   
    uint256 private constant MAX = ~uint256(0);
    uint256 private constant _tTotal = 10000000000 * 10**18;
    uint256 private _rTotal = (MAX - (MAX % _tTotal));
    uint256 private _tFeeTotal;

    string private constant _name = "Alpha";
    string private constant _symbol = "ALPHA";
    uint8 private constant _decimals = 18;

    address public _deadAddress = 0x000000000000000000000000000000000000dEaD;
    address payable public _marketingWallet;
    
    uint256 public _taxFee = 2;
    uint256 private _previousTaxFee = _taxFee;
    uint256 private constant _maxTaxFee = 2;
    
    uint256 public _liquidityFee = 9; // this is split ~3% liquidity (33% of 9), ~6% marketing(67% of 9)
    uint256 private _previousLiquidityFee = _liquidityFee;
    uint256 private constant _maxLiquidityFee = 9;
    
    uint256 public _slipPercent = 80; // this allows for a slippage of ~20%
    
    uint public timeSalesTaxEnabled;
    bool public salesTaxEnabled = false;

    IUniswapV2Router02 public immutable uniswapV2Router;
    address public immutable uniswapV2Pair;
    
    bool inSwapAndLiquify;
    bool public swapAndLiquifyEnabled = true;
    
    uint256 public _maxTxAmount = 50000000 * 10**18; // this is 0.5% of total coins
    uint256 private numTokensSellToAddToLiquidity = 5000000 * 10**18;
    uint256 private _maxWalletSize = 100000000 * 10**18; // this 1% of total coins

    uint256 private constant _minMaxTxAmount = 50000000 * 10**18;
    uint256 private constant _minMaxWalletSize = 100000000 * 10**18;

    event botAddedToBlacklist(address account);
    event botRemovedFromBlacklist(address account);

    event TaxFeeUpdated(uint256 taxFee);
    event LiquidityFeeUpdated(uint256 liquidityFee);
    event ExcludeFromRewardUpdated(address account);
    event IncludeInRewardUpdated(address account);
    event ExcludeFromFeeUpdated(address account);
    event IncludeInFeeUpdated(address account);
    event MaxTxAmountUpdated(uint256 _maxTxAmount);
    event MaxWalletSizeUpdated(uint256 _maxWalletSize);
    event BoughtAndBurnedTokens(uint256 amount);
    event ChangedSlipPercent(uint256 percent);
    event ToggledSalesTax(bool state);

    event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
    event SwapAndLiquifyEnabledUpdated(bool enabled);
    event SwapAndLiquify(
        uint256 tokensSwapped,
        uint256 ethReceived,
        uint256 tokensIntoLiquidity
    );
    
    modifier lockTheSwap {
        inSwapAndLiquify = true;
        _;
        inSwapAndLiquify = false;
    }
    
    constructor (address payable marketingWalletAddress) {
        
        _marketingWallet = marketingWalletAddress;

        _rOwned[_msgSender()] = _rTotal;
        
        IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); 
         // Create a uniswap pair for this new token
        uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
            .createPair(address(this), _uniswapV2Router.WETH());

        // set the rest of the contract variables
        uniswapV2Router = _uniswapV2Router;
        
        //exclude owner and this contract from fee
        _isExcludedFromFee[owner()] = true;
        _isExcludedFromFee[address(this)] = true;
        _isExcludedFromFee[_deadAddress] = true;
        
        // exclude dead address from reward
        _isExcluded[_deadAddress] = true;

        // enable 24hr sales tax to protect from bots
        toggleSalesTax(true);
        
        emit Transfer(address(0), _msgSender(), _tTotal);
    }

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

    function balanceOf(address account) public view override returns (uint256) {
        if (_isExcluded[account]) return _tOwned[account];
        return tokenFromReflection(_rOwned[account]);
    }

    function transfer(address recipient, uint256 amount) public override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

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

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

    function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount);
        return true;
    }

    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
        return true;
    }

    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue);
        return true;
    }

    function isExcludedFromReward(address account) public view returns (bool) {
        return _isExcluded[account];
    }

    function isBlackListed(address account) public view returns (bool) {
        return _isBlackListedBot[account];
    }

    function totalFees() public view returns (uint256) {
        return _tFeeTotal;
    }

    function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
        require(tAmount <= _tTotal, "Amount must be less than supply");
        if (!deductTransferFee) {
            (uint256 rAmount,,,,,) = _getValues(tAmount);
            return rAmount;
        } else {
            (,uint256 rTransferAmount,,,,) = _getValues(tAmount);
            return rTransferAmount;
        }
    }

    function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
        require(rAmount <= _rTotal, "Amount must be less than total reflections");
        uint256 currentRate =  _getRate();
        return rAmount / currentRate;
    }

    function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
        (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
        _tOwned[sender] = _tOwned[sender] - tAmount;
        _rOwned[sender] = _rOwned[sender] - rAmount;
        _tOwned[recipient] = _tOwned[recipient] + tTransferAmount;
        _rOwned[recipient] = _rOwned[recipient] + rTransferAmount;        
        _takeLiquidity(tLiquidity);
        _reflectFee(rFee, tFee);
        emit Transfer(sender, recipient, tTransferAmount);
    }
    
     //to receive ETH from uniswapV2Router when swapping
    receive() external payable {}

    function _reflectFee(uint256 rFee, uint256 tFee) private {
        _rTotal = _rTotal - rFee;
        _tFeeTotal = _tFeeTotal + tFee;
    }

    function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
        (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
        (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
        return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
    }

    function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
        uint256 tFee = calculateTaxFee(tAmount);
        uint256 tLiquidity = calculateLiquidityFee(tAmount);
        uint256 tTransferAmount = tAmount - tFee - tLiquidity;
        return (tTransferAmount, tFee, tLiquidity);
    }

    function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
        uint256 rAmount = tAmount * currentRate;
        uint256 rFee = tFee * currentRate;
        uint256 rLiquidity = tLiquidity * currentRate;
        uint256 rTransferAmount = rAmount - rFee - rLiquidity;
        return (rAmount, rTransferAmount, rFee);
    }

    function _getRate() private view returns(uint256) {
        (uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
        return rSupply / tSupply;
    }

    function _getCurrentSupply() private view returns(uint256, uint256) {
        uint256 rSupply = _rTotal;
        uint256 tSupply = _tTotal;      
        for (uint256 i = 0; i < _excluded.length; i++) {
            if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
            rSupply = rSupply - _rOwned[_excluded[i]];
            tSupply = tSupply - _tOwned[_excluded[i]];
        }
        if (rSupply < (_rTotal / _tTotal)) return (_rTotal, _tTotal);
        return (rSupply, tSupply);
    }
    
    function _takeLiquidity(uint256 tLiquidity) private {
        uint256 currentRate =  _getRate();
        uint256 rLiquidity = tLiquidity * currentRate;
        _rOwned[address(this)] = _rOwned[address(this)] + rLiquidity;
        if(_isExcluded[address(this)])
            _tOwned[address(this)] = _tOwned[address(this)] + tLiquidity;
    }
    
    function calculateTaxFee(uint256 _amount) private view returns (uint256) {
        return (_amount * _taxFee) / (10**2);
    }

    function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
        return (_amount * _liquidityFee) / (10**2);
    }

    function toggleSalesTax(bool state) private {
        timeSalesTaxEnabled = block.timestamp;
        salesTaxEnabled = state;
    }
    
    function removeAllFee() private {
        if(_taxFee == 0 && _liquidityFee == 0) return;
        
        _previousTaxFee = _taxFee;
        _previousLiquidityFee = _liquidityFee;
        
        _taxFee = 0;
        _liquidityFee = 0;
    }
    
    function restoreAllFee() private {
        _taxFee = _previousTaxFee;
        _liquidityFee = _previousLiquidityFee;
    }
    
    function isExcludedFromFee(address account) public view returns(bool) {
        return _isExcludedFromFee[account];
    }

    function isBlacklisted(address account) public view returns(bool) {
        return _isBlackListedBot[account];
    }

    function _approve(address owner, address spender, uint256 amount) private {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

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

    function _transfer(
        address from,
        address to,
        uint256 amount
    ) private {

        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");
        require(amount > 0, "Transfer amount must be greater than zero");

        require(!_isBlackListedBot[from], "You are blacklisted");
        require(!_isBlackListedBot[msg.sender], "You are blacklisted");
        require(!_isBlackListedBot[tx.origin], "You are blacklisted");
        require(!_isBlackListedBot[to], "Recipient is blacklisted");

        if(from != owner() && to != owner())
            require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");

        if(from != owner() && to != owner() && to != uniswapV2Pair && to != address(0xdead)) {
            uint256 tokenBalanceTo = balanceOf(to);
            require(tokenBalanceTo + amount <= _maxWalletSize, "Recipient exceeds max wallet size.");
        }

        // is the token balance of this contract address over the min number of
        // tokens that we need to initiate a swap + liquidity lock?
        // also, don't get caught in a circular liquidity event.
        // also, don't swap & liquify if sender is uniswap pair.
        uint256 contractTokenBalance = balanceOf(address(this));
        
        if(contractTokenBalance >= _maxTxAmount)
        {
            contractTokenBalance = _maxTxAmount;
        }
        
        bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
        if (
            overMinTokenBalance &&
            !inSwapAndLiquify &&
            from != uniswapV2Pair &&
            swapAndLiquifyEnabled
        ) {
            contractTokenBalance = numTokensSellToAddToLiquidity;
            //add liquidity
            swapAndLiquify(contractTokenBalance);
        }
        
        //indicates if fee should be deducted from transfer
        bool takeFee = true;
        
        //if any account belongs to _isExcludedFromFee account then remove the fee
        if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
            takeFee = false;
        }
        
        //transfer amount, it will take tax, burn, liquidity fee
        _tokenTransfer(from,to,amount,takeFee);
    }

    function swapAndLiquify(uint256 amount) private lockTheSwap {

        // get portion for marketing/liquidity
        uint256 marketingAmt = (amount * 67) / (10**2);
        uint256 liquidityAmt = amount - marketingAmt;
        
        // send eth to marketing
        uint256 marketingBalance = swapTokensGetBalance(marketingAmt);
        _marketingWallet.transfer(marketingBalance);

        // split the liquidity amount into halves
        uint256 half = liquidityAmt/2;
        uint256 otherHalf = liquidityAmt - half;

        uint256 newBalance = swapTokensGetBalance(half);

        // add liquidity to uniswap
        addLiquidity(otherHalf, newBalance);
        
        emit SwapAndLiquify(half, newBalance, otherHalf);
    }

    function swapTokensGetBalance(uint256 amount) private returns(uint256) {
        // capture the contract's current ETH balance.
        // this is so that we can capture exactly the amount of ETH that the
        // swap creates, and not make the liquidity event include any ETH that
        // has been manually sent to the contract
        uint256 initialBalance = address(this).balance;

        // swap tokens for ETH
        swapTokensForEth(amount); 

        // how much ETH did we just swap into?
        uint256 newBalance = address(this).balance - initialBalance;

        return newBalance;
    }

    function swapTokensForEth(uint256 tokenAmount) private {
        // generate the uniswap pair path of token -> weth
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = uniswapV2Router.WETH();

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

        uint[] memory amountOutMins = uniswapV2Router.getAmountsOut(tokenAmount, path);
        uint256 minEth = (amountOutMins[1] * _slipPercent) / 100;

        // make the swap
        uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenAmount,
            minEth,
            path,
            address(this),
            block.timestamp
        );
    }

    function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
        // approve token transfer to cover all possible scenarios
        _approve(address(this), address(uniswapV2Router), tokenAmount);

        uint256 minToken = (tokenAmount * _slipPercent) / 100;
        uint256 minEth = (ethAmount * _slipPercent) / 100;

        // add the liquidity
        uniswapV2Router.addLiquidityETH{value: ethAmount}(
            address(this),
            tokenAmount,
            minToken,
            minEth,
            owner(),
            block.timestamp
        );
    }

    //this method is responsible for taking all fee, if takeFee is true
    function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
        // if this is a sale and we're within the 24hr window, make total tax 25%
        bool isSale = recipient == uniswapV2Pair;
        bool isWithinTime = block.timestamp <= timeSalesTaxEnabled + 1 days;
        uint256 tmpPrevLiqFee = _liquidityFee;
        if(salesTaxEnabled && isSale && isWithinTime) {
            _liquidityFee = 23;
        }
        
        if(!takeFee)
            removeAllFee();
        
        if (_isExcluded[sender] && !_isExcluded[recipient]) {
            _transferFromExcluded(sender, recipient, amount);
        } else if (!_isExcluded[sender] && _isExcluded[recipient]) {
            _transferToExcluded(sender, recipient, amount);
        } else if (_isExcluded[sender] && _isExcluded[recipient]) {
            _transferBothExcluded(sender, recipient, amount);
        } else {
            _transferStandard(sender, recipient, amount);
        }
        
        if(!takeFee)
            restoreAllFee();

        if(salesTaxEnabled) {
            _liquidityFee = tmpPrevLiqFee;
        }

        // if we're past the 24 hours, disable the sales tax
        if(salesTaxEnabled && !isWithinTime) {
            toggleSalesTax(false);
        }
    }

    function _transferStandard(address sender, address recipient, uint256 tAmount) private {
        (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
        _rOwned[sender] = _rOwned[sender] - rAmount;
        _rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
        _takeLiquidity(tLiquidity);
        _reflectFee(rFee, tFee);
        emit Transfer(sender, recipient, tTransferAmount);
    }

    function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
        (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
        _rOwned[sender] = _rOwned[sender] - rAmount;
        _tOwned[recipient] = _tOwned[recipient] + tTransferAmount;
        _rOwned[recipient] = _rOwned[recipient] + rTransferAmount;           
        _takeLiquidity(tLiquidity);
        _reflectFee(rFee, tFee);
        emit Transfer(sender, recipient, tTransferAmount);
    }

    function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
        (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
        _tOwned[sender] = _tOwned[sender] - tAmount;
        _rOwned[sender] = _rOwned[sender] - rAmount;
        _rOwned[recipient] = _rOwned[recipient] + rTransferAmount;   
        _takeLiquidity(tLiquidity);
        _reflectFee(rFee, tFee);
        emit Transfer(sender, recipient, tTransferAmount);
    }


    /////////////////////////////////////////////onlyOwner()////////////////////////////////////////////////////
    function excludeFromFee(address account) public onlyOwner {
        _isExcludedFromFee[account] = true;
        emit ExcludeFromFeeUpdated(account);
    }
    
    function includeInFee(address account) public onlyOwner {
        _isExcludedFromFee[account] = false;
        emit IncludeInFeeUpdated(account);
    }    

    function excludeFromReward(address account) public onlyOwner() {
        // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
        require(!_isExcluded[account], "Account is already excluded");
        if(_rOwned[account] > 0) {
            _tOwned[account] = tokenFromReflection(_rOwned[account]);
        }
        _isExcluded[account] = true;
        _excluded.push(account);
        emit ExcludeFromRewardUpdated(account);
    }

    function includeInReward(address account) external onlyOwner() {
        require(_isExcluded[account], "Account is not excluded");
        for (uint256 i = 0; i < _excluded.length; i++) {
            if (_excluded[i] == account) {
                _excluded[i] = _excluded[_excluded.length - 1];
                _tOwned[account] = 0;
                _isExcluded[account] = false;
                _excluded.pop();
                break;
            }
        }
        emit IncludeInRewardUpdated(account);
    }
    
    function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
        require(taxFee <= _maxTaxFee, "Tax fee must be less than or equal to _maxTaxFee");
        _taxFee = taxFee;
        emit TaxFeeUpdated(taxFee);
    }
    
    function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
        require(liquidityFee <= _maxLiquidityFee, "Liquidity fee must be less than or equal to _maxLiquidityFee");
        _liquidityFee = liquidityFee;
        emit LiquidityFeeUpdated(liquidityFee);
    }
   
    function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
        _maxTxAmount = (_tTotal * maxTxPercent) / (10**2);
        
        require(_maxTxAmount >= _minMaxTxAmount, "Max Tax percent too low, must be greater than or equal to _minMaxTxAmount");
        emit MaxTxAmountUpdated(_maxTxAmount);
    }

    function setMaxWalletSizePercent(uint256 maxWalletSizePercent) external onlyOwner() {
       _maxWalletSize = (_tTotal * maxWalletSizePercent) / (10**2);
       
       require(_maxWalletSize >= _minMaxWalletSize, "Max Wallet Size percent too low, must be greater than or equal to _minMaxWalletSize");
       emit MaxWalletSizeUpdated(_maxWalletSize);
    }

    function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
       swapAndLiquifyEnabled = _enabled;
       emit SwapAndLiquifyEnabledUpdated(_enabled);
    }

    function buyBackAndBurnTokens(uint256 amount) external onlyOwner() {
        if(!inSwapAndLiquify && amount > 0 && amount <= address(this).balance) {
            // get contracts balance of tokens
            uint256 initialTokenBalance = balanceOf(address(this));
            
            // swap eth for the tokens
            address[] memory path = new address[](2);
            path[0] = uniswapV2Router.WETH();
            path[1] = address(this);

            uint[] memory amountOutMins = uniswapV2Router.getAmountsOut(amount, path);
            uint256 minTokens = (amountOutMins[1] * _slipPercent) / 100;

            // make the swap
            uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(
                minTokens,
                path,
                address(this),
                block.timestamp
            );

            // get amount of tokens we swapped into
            uint256 swappedTokenBalance = balanceOf(address(this)) - initialTokenBalance;

            // burn the tokens
            transfer(_deadAddress, swappedTokenBalance);
            emit BoughtAndBurnedTokens(amount);
        }
    }

    function addBotToBlacklist(address account) external onlyOwner() {
       require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, "Can't blacklist UniSwap router");
       require(!_isBlackListedBot[account], "Account is already blacklisted");
       _isBlackListedBot[account] = true;
    }

    function removeBotFromBlacklist(address account) external onlyOwner() {
      require(_isBlackListedBot[account], "Account is not blacklisted");
      _isBlackListedBot[account] = false;
    }

    function changeSlipPercent(uint256 percent) external onlyOwner() {
      require(percent < 100, "Slippage percent must be less than 100%");
      _slipPercent = percent;
      emit ChangedSlipPercent(percent);
    }

    function ownerToggleSalesTax(bool state) external onlyOwner() {
      toggleSalesTax(state);
      emit ToggledSalesTax(state);
    }

}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function excludeFromFee(address account) public onlyOwner {
    _isExcludedFromFee[account] = true;
    emit ExcludeFromFeeUpdated(account);
}

/////////////////////////////////////////////onlyOwner()////////////////////////////////////////////////////