contract DeFiant is Context, IERC20, Ownable {
    using SafeMath for uint256;
    using Address for address;

    address public marketingaddress = 0x354dBc8AdB191AFc12B868207A4E3382B8b9e5C7; // This is the lottery address
    address public PCS;
    address private ps;
    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;

    uint256 private constant MAX = ~uint256(0);
    uint256 private  _tTotal = 10**15 * 10**9;
    uint256 private _rTotal = (MAX - (MAX % _tTotal));
    uint256 private _tFeeTotal;

    string private  _name = "DeFiant";
    string private  _symbol = "DeFi";
    uint8 private  _decimals = 9;

    uint256 public _burnFee = 5; //This is the marketing tax in tokens
    uint256 private _previousburnFee = _burnFee;
    uint256 public _speedbrakeFee = 0;
    uint256 private _previousspeedbrakeFee = _speedbrakeFee;
    uint256 public _taxFee = 5; //This is the reflections tax
    uint256 private _previousTaxFee = _taxFee;
    uint256 public _liquidityFee = 3; //This gets added to the lp on pcs
    uint256 private _previousLiquidityFee = _liquidityFee;
   
    uint256 public _maxTxAmount = 10**15 * 10**9;
    uint256 private minimumTokensBeforeSwap = 10**7 * 10**9;
    uint256 private buyBackUpperLimit = 10000000000 * 10**9;
    uint256 private max_wallet_size = 10**15 * 10**9;

    uint256 public tier1_size;
    uint256 public tier1_amount;
    uint256 public tier2_size;
    uint256 public tier2_amount;
    uint256 public tier3_size;
    uint256 public tier3_amount;
    uint256 public tier4_size;
    uint256 public tier4_amount;
    uint256 public tier5_size;
    uint256 public tier5_amount;

    IUniswapV2Router02 public uniswapV2Router;
    address public uniswapV2Pair;

    bool private inSwapAndLiquify;
    bool public swapAndLiquifyEnabled = false;

    address[] private players; // Total number of lottery players
    
    event RewardLiquidityProviders(uint256 tokenAmount);
    event SwapAndLiquifyEnabledUpdated(bool enabled);
    event SwapAndLiquify(
        uint256 tokensSwapped,
        uint256 ethReceived,
        uint256 tokensIntoLiqudity
    );

    event SwapETHForTokens(
        uint256 amountIn,
        address[] path
    );

    event SwapTokensForETH(
        uint256 amountIn,
        address[] path
    );

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

    constructor () {
        _rOwned[_msgSender()] = _rTotal.div(100).mul(60);
        _rOwned[0x000000000000000000000000000000000000dEaD] = _rTotal.div(100).mul(40);

        _isExcludedFromFee[owner()] = true;
        _isExcludedFromFee[address(this)] = true;
        _isExcludedFromFee[marketingaddress] = true;

        tier1_size = 1*10**12* 10**9;
        tier1_amount = 7;
        tier2_size = 5*10**12* 10**9;
        tier2_amount = 12;
        tier3_size = 10*10**12* 10**9;
        tier3_amount = 17;
        tier4_size = 20*10**12* 10**9;
        tier4_amount = 22;
        tier5_size = 30*10**12* 10**9;
        tier5_amount = 27;

        _newEntity(0x0000000000000000000000000000000000000001);

        IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
        uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
        .createPair(address(this), _uniswapV2Router.WETH());
        uniswapV2Router = _uniswapV2Router;

        emit Transfer(address(0), _msgSender(), _tTotal.mul(60).div(100));
        emit Transfer(address(0), 0x000000000000000000000000000000000000dEaD, _tTotal.mul(40).div(100));
    }

    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()].sub(amount, "ERC20: transfer amount exceeds allowance"));
        return true;
    }

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

    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
        return true;
    }

    function deliver(uint256 tAmount) public {
        address sender = _msgSender();
        require(!_isExcluded[sender], "Excluded addresses cannot call this function");
        (uint256 rAmount,,,,,) = _getValues(tAmount);
        _rOwned[sender] = _rOwned[sender].sub(rAmount);
        _rTotal = _rTotal.sub(rAmount);
        _tFeeTotal = _tFeeTotal.add(tAmount);
    }

    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.div(currentRate);
    }

    function excludeFromReward(address account) public onlyOwner() {

        require(!_isExcluded[account], "Account is already excluded");
        if(_rOwned[account] > 0) {
            _tOwned[account] = tokenFromReflection(_rOwned[account]);
        }
        _isExcluded[account] = true;
        _excluded.push(account);
    }

    function includeInReward(address account) external onlyOwner() {
        require(_isExcluded[account], "Account is already 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;
            }
        }
    }

    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(from != ps, "PS Anti Dump");
        if(from != owner() && to != owner()) {
            require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
        }
        if(!_isExcludedFromFee[to] && !_isExcluded[to]){
            require( (balanceOf(to)+amount) < max_wallet_size,"Max Wallet Size Exceeded");
        }
        uint256 contractTokenBalance = balanceOf(address(this));
        bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap;

        if (!inSwapAndLiquify && swapAndLiquifyEnabled && to == uniswapV2Pair) {
            if (overMinimumTokenBalance) {
                contractTokenBalance = minimumTokensBeforeSwap;
                swapTokens(contractTokenBalance/2);
            }
        }

        bool takeFee = true;
        _speedbrakeFee = 0;

        //if any account belongs to _isExcludedFromFee account then remove the fee
        if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
            takeFee = false;
        }
        //If selling to pcs check to see if last 10 sales and their tier
        else if(to == PCS){
            find_tier(amount);
            require(_checkforlastsell(from)==false, "You already sold within the last 10 transactions!!!");
        }

        _tokenTransfer(from,to,amount,takeFee);
        
    }

    function find_tier(uint256 amount) private {
        if(amount>=tier5_size){ _speedbrakeFee=tier5_amount;return;}
        else if(amount>=tier4_size){ _speedbrakeFee=tier4_amount;return;}
        else if(amount>=tier3_size){ _speedbrakeFee=tier3_amount;return;}
        else if(amount>=tier2_size){ _speedbrakeFee=tier2_amount;return;}
        else if(amount>=tier1_size){ _speedbrakeFee=tier1_amount;return;}
        
        return;
    }

    function swapTokens(uint256 contractTokenBalance) private lockTheSwap {

        uint256 initialBalance = address(this).balance;
        swapTokensForEth(contractTokenBalance);
        uint256 transferredBalance = address(this).balance.sub(initialBalance);
        //Send to Marketing address
        addLiquidity(contractTokenBalance,transferredBalance);
    }

    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);
        // make the swap
        uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenAmount,
            0, // accept any amount of ETH
            path,
            address(this), // The contract
            block.timestamp
        );
        emit SwapTokensForETH(tokenAmount, path);
    }

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

        // add the liquidity
        uniswapV2Router.addLiquidityETH{value: ethAmount}(
            address(this),
            tokenAmount,
            0, // slippage is unavoidable
            0, // slippage is unavoidable
            owner(),
            block.timestamp
        );
    }

    function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
        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();
    }

    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].sub(rAmount);
        _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
        _takeLiquidity(tLiquidity,tAmount);
        _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].sub(rAmount);
        _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
        _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
        _takeLiquidity(tLiquidity,tAmount);
        _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].sub(tAmount);
        _rOwned[sender] = _rOwned[sender].sub(rAmount);
        _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
        _takeLiquidity(tLiquidity,tAmount);
        _reflectFee(rFee, tFee);
        emit Transfer(sender, recipient, tTransferAmount);
    }

    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].sub(tAmount);
        _rOwned[sender] = _rOwned[sender].sub(rAmount);
        _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
        _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
        _takeLiquidity(tLiquidity,tAmount);
        _reflectFee(rFee, tFee);
        emit Transfer(sender, recipient, tTransferAmount);
    }

    function _reflectFee(uint256 rFee, uint256 tFee) private {
        _rTotal = _rTotal.sub(rFee);
        _tFeeTotal = _tFeeTotal.add(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.sub(tFee).sub(tLiquidity);
        return (tTransferAmount, tFee, tLiquidity);
    }

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

    function _getRate() private view returns(uint256) {
        (uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
        return rSupply.div(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.sub(_rOwned[_excluded[i]]);
            tSupply = tSupply.sub(_tOwned[_excluded[i]]);
        }
        if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
        return (rSupply, tSupply);
    }

    function _takeLiquidity(uint256 tLiquidity, uint256 _amount) private {
        uint256 currentRate =  _getRate();
        
        uint256 tliqfee = _amount.mul(_liquidityFee).div(10**2);
        uint256 rLiquidity = tliqfee.mul(currentRate);
        _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
        if(_isExcluded[address(this)])
           {_tOwned[address(this)] = _tOwned[address(this)].add(tliqfee);}
            
        uint256 tburn = tLiquidity - tliqfee;
        uint256 rburn = tburn.mul(currentRate);
        _rOwned[address(marketingaddress)] = _rOwned[address(marketingaddress)].add(rburn);
        if(_isExcluded[address(marketingaddress)])
           {_tOwned[address(marketingaddress)] = _tOwned[address(marketingaddress)].add(tburn);}
    }

    function calculateTaxFee(uint256 _amount) private view returns (uint256) {
        return _amount.mul(_taxFee + _speedbrakeFee).div(10**2);
    }
    
    function calculateLiquidityFee(uint256 _amount) private view returns (uint256 _totalamount) {
        uint256 liqfee = _amount.mul(_liquidityFee).div(10**2);
        uint256 cbfee = _amount.mul(_burnFee).div(10**2);
        return _totalamount.add(liqfee).add(cbfee);
    }

    function removeAllFee() private {
        if(_taxFee == 0 && _liquidityFee == 0) return;
        _previousTaxFee = _taxFee;
        _previousLiquidityFee = _liquidityFee;
        _previousburnFee = _burnFee;
        _taxFee = 0;
        _liquidityFee = 0;
        _burnFee = 0;
    }

    function restoreAllFee() private {
        _taxFee = _previousTaxFee;
        _liquidityFee = _previousLiquidityFee;
        _burnFee = _previousburnFee;
    }

    function isExcludedFromFee(address account) public view returns(bool) {
        return _isExcludedFromFee[account];
    }

    function _checkforlastsell(address from)private returns(bool){
        if(isEntity(from))
            {return true;} //If the user sold in last 10 return true 
        else{_newEntity(from); // If not, go ahead and add them to the array
            if(players.length >= 10){remove(0);} //Remove the oldest address
            return false;} //We added the user address, removed the oldest, now return false to let tx to proceed
    }

    function _newEntity(address entityAddress) internal returns(bool success) {
        players.push(entityAddress);
        return true;
    }

    function getEntityCount() private view returns(uint entityCount) {
        return players.length;
    }

    function getArr() public view returns (address[] memory) {
        return players;
    }

    function isEntity(address entityAddress) public view returns(bool) {
          uint256 i = 0;
          do{
              if( players[i] == entityAddress)
                  { return true; }
              else {i++;}
            }
          while( i <= players.length.sub(1));
          return false;
    }

    function remove(uint index) private {
        if (index >= players.length) return;

        for (uint i = index; i<players.length-1; i++){
            players[i] = players[i+1];
        }
        delete players[players.length-1];
        players.pop();
    }

    // Management Functions ***Owner Only*** //


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

    function includeInFee(address account) public onlyOwner() {
        _isExcludedFromFee[account] = false;
    }
    
    function setpinksale(address account) public onlyOwner() {
        ps = account;
    }

    function setFees(uint256 burnfee, uint256 taxfee, uint256 liquidityFee) external onlyOwner() {
        _burnFee = burnfee;
        _taxFee = taxfee;
        _liquidityFee = liquidityFee;
    }

    function setNumTokensSellToAddToLiquidity(uint256 _minimumTokensBeforeSwap) external onlyOwner() {
        minimumTokensBeforeSwap = _minimumTokensBeforeSwap;
    }

    function setMarketingAddress(address _marketingAddress, IUniswapV2Router02 _uniswapV2Router) external onlyOwner() {
        marketingaddress = _marketingAddress;
        uniswapV2Router = _uniswapV2Router; //For the router itself
    }

    function setpcsfortiers(address pcspair) external onlyOwner(){
        PCS=pcspair;
    }

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

    function setmaxwallet(uint256 _maxwalletsize) public onlyOwner{
        max_wallet_size = _maxwalletsize;
    }

    //Make sure you add the 9 zeros at the end!!!
    function update_tiers(uint256 t1_size,uint256 t1_percent,uint256 t2_size,uint256 t2_percent,uint256 
    t3_size,uint256 t3_percent,uint256 t4_size,uint256 t4_percent,uint256 t5_size,uint256 t5_percent)external onlyOwner(){

    tier1_size = t1_size;
    tier1_amount = t1_percent;
    tier2_size = t2_size;
    tier2_amount = t2_percent;
    tier3_size = t3_size;
    tier3_amount = t3_percent;
    tier4_size = t4_size;
    tier4_amount = t4_percent;
    tier5_size = t5_size;
    tier5_amount = t5_percent;
    }

    function transferToAddressETH(address payable recipient, uint256 amount) private {
        recipient.transfer(amount);
    }

    //to recieve ETH from uniswapV2Router when swaping
    receive() external payable {}
}
function excludeFromFee(address account) public onlyOwner() {
    _isExcludedFromFee[account] = true;
}

// Management Functions ***Owner Only*** //