contract HyperShiba is ERC20, Ownable {
    using SafeMath for uint256;

    IUniswapV2Router02 public uniswapV2Router;
    address public  uniswapV2Pair;

    bool private swapping;

    HshibDividendTracker public dividendTracker;

    address public deadWallet = 0x000000000000000000000000000000000000dEaD;
   

    address public immutable USDT = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); // USDT

    uint256 public swapTokensAtAmount = 4000000 * (10**18);
    
    mapping(address => bool) public _isBlacklisted;
    
  

    uint256 public USDTRewardsFee = 4;
    uint256 public marketingFee = 4;
    uint256 public buybackFee = 4;
    uint256 public totalFees = USDTRewardsFee.add(buybackFee).add(marketingFee);

    address public _marketingWalletAddress = 0x6b752ABF5a28dA2A81EcA05e7EC3E4DbD3E1466F;
    address public _buybackWalletAddress = 0x23bd72dbEEA5bAd872Aa1E10Aef2042fB319B7c9;


    // use by default 300,000 gas to process auto-claiming dividends
    uint256 public gasForProcessing = 300000;

     // exlcude from fees and max transaction amount
    mapping (address => bool) private _isExcludedFromFees;

    mapping(address => bool) private _isExcludedFromAntiWhale;

    uint256 public maxTransferAmountRate = 1000;
    
    bool private enableAntiwhale = false;


    // store addresses that a automatic market maker pairs. Any transfer *to* these addresses
    // could be subject to a maximum transfer amount
    mapping (address => bool) public automatedMarketMakerPairs;

    event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress);

    event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);

    event ExcludeFromFees(address indexed account, bool isExcluded);
    event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);

    event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);

    event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);

    event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);

    event SwapAndLiquify(
        uint256 tokensSwapped,
        uint256 ethReceived,
        uint256 tokensIntoLiqudity
    );

    event SendDividends(
    	uint256 tokensSwapped,
    	uint256 amount
    );

    event ProcessedDividendTracker(
    	uint256 iterations,
    	uint256 claims,
        uint256 lastProcessedIndex,
    	bool indexed automatic,
    	uint256 gas,
    	address indexed processor
    );

    constructor() public ERC20("Hyper Shiba Inu", "HSHIB") {

        address _newOwner = 0x24BEfE13C8A4CaB0F1Fe4Be51D9fF6dbF97aBF59;
    	dividendTracker = new HshibDividendTracker();

    	IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
         // Create a uniswap pair for this new token
        address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
            .createPair(address(this), _uniswapV2Router.WETH());

        uniswapV2Router = _uniswapV2Router;
        uniswapV2Pair = _uniswapV2Pair;

        _setAutomatedMarketMakerPair(_uniswapV2Pair, true);

        // exclude from receiving dividends
        dividendTracker.excludeFromDividends(address(dividendTracker));
        dividendTracker.excludeFromDividends(address(this));
        dividendTracker.excludeFromDividends(_newOwner);
        dividendTracker.excludeFromDividends(deadWallet);
        dividendTracker.excludeFromDividends(address(_uniswapV2Router));

        // exclude from paying fees or having max transaction amount
        excludeFromFees(_newOwner, true);
        excludeFromFees(_marketingWalletAddress, true);
        excludeFromFees(_buybackWalletAddress, true);
        excludeFromFees(address(this), true);

        _isExcludedFromAntiWhale[_newOwner]                 = true;
        _isExcludedFromAntiWhale[deadWallet]              = true;
        _isExcludedFromAntiWhale[address(this)]           = true;

        /*
            _mint is an internal function in ERC20.sol that is only called here,
            and CANNOT be called ever again
        */
        _mint(_newOwner, 1000000000000000 * (10**18));
    }

    modifier antiWhale(address sender, address recipient, uint256 amount) {
        if (enableAntiwhale && maxTransferAmount() > 0 && !automatedMarketMakerPairs[sender]) {
            if (
                _isExcludedFromAntiWhale[sender] == false
                && _isExcludedFromAntiWhale[recipient] == false
            ) {
                require(amount <= maxTransferAmount(), "AntiWhale: Transfer amount exceeds the maxTransferAmount");
            }
        }
        _;
    }

    receive() external payable {

  	}

    function setExcludedFromAntiWhale(address account, bool exclude) public onlyOwner {
          _isExcludedFromAntiWhale[account] = exclude;
    }

    function isExcludedFromAntiWhale(address account) public view returns(bool) {
        return _isExcludedFromAntiWhale[account];
    }

    function updateDividendTracker(address newAddress) public onlyOwner {
        require(newAddress != address(dividendTracker), "HSHIB Token: The dividend tracker already has that address");

        HshibDividendTracker newDividendTracker = HshibDividendTracker(payable(newAddress));

        require(newDividendTracker.owner() == address(this), "HSHIB Token: The new dividend tracker must be owned by the HSHIB Token contract");

        newDividendTracker.excludeFromDividends(address(newDividendTracker));
        newDividendTracker.excludeFromDividends(address(this));
        newDividendTracker.excludeFromDividends(owner());
        newDividendTracker.excludeFromDividends(deadWallet);
        newDividendTracker.excludeFromDividends(address(uniswapV2Router));

        emit UpdateDividendTracker(newAddress, address(dividendTracker));

        dividendTracker = newDividendTracker;
    }

    function updateUniswapV2Router(address newAddress) public onlyOwner {
        require(newAddress != address(uniswapV2Router), "HSHIB Token: The router already has that address");
        emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
        uniswapV2Router = IUniswapV2Router02(newAddress);
        address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
            .createPair(address(this), uniswapV2Router.WETH());
        uniswapV2Pair = _uniswapV2Pair;
    }

    function excludeFromFees(address account, bool excluded) public onlyOwner {
        require(_isExcludedFromFees[account] != excluded, "HSHIB Token: Account is already the value of 'excluded'");
        _isExcludedFromFees[account] = excluded;

        emit ExcludeFromFees(account, excluded);
    }

    function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
        for(uint256 i = 0; i < accounts.length; i++) {
            _isExcludedFromFees[accounts[i]] = excluded;
        }

        emit ExcludeMultipleAccountsFromFees(accounts, excluded);
    }

    function setSwapTokensAtAmount(uint256 amount) external onlyOwner{
        swapTokensAtAmount = amount;
    }

    function setMarketingWallet(address payable wallet) external onlyOwner{
        _marketingWalletAddress = wallet;
    }


    function setUSDTRewardsFee(uint256 value) external onlyOwner{
        USDTRewardsFee = value;
        totalFees = USDTRewardsFee.add(marketingFee).add(buybackFee);
        require(totalFees < 20, "Total Fees should be < 20 !");
    }

    function setBuyBackFee(uint256 value) external onlyOwner{
        buybackFee = value;
        totalFees = USDTRewardsFee.add(marketingFee).add(buybackFee);
        require(totalFees < 20, "Total Fees should be < 20 !");
    }

    function setMarketingFee(uint256 value) external onlyOwner{
        marketingFee = value;
        totalFees = USDTRewardsFee.add(marketingFee).add(buybackFee);
        require(totalFees < 20, "Total Fees should be < 20 !");
    }


    function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
        require(pair != uniswapV2Pair, "HSHIB Token: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");

        _setAutomatedMarketMakerPair(pair, value);
    }
    
    function blacklistAddress(address account, bool value) external onlyOwner{
        _isBlacklisted[account] = value;
    }

    function _setAutomatedMarketMakerPair(address pair, bool value) private {
        require(automatedMarketMakerPairs[pair] != value, "HSHIB Token: Automated market maker pair is already set to that value");
        automatedMarketMakerPairs[pair] = value;

        if(value) {
            dividendTracker.excludeFromDividends(pair);
        }

        emit SetAutomatedMarketMakerPair(pair, value);
    }

    function updateGasForProcessing(uint256 newValue) public onlyOwner {
        require(newValue >= 200000 && newValue <= 500000, "HSHIB Token: gasForProcessing must be between 200,000 and 500,000");
        require(newValue != gasForProcessing, "HSHIB Token: Cannot update gasForProcessing to same value");
        emit GasForProcessingUpdated(newValue, gasForProcessing);
        gasForProcessing = newValue;
    }

    function updateClaimWait(uint256 claimWait) external onlyOwner {
        dividendTracker.updateClaimWait(claimWait);
    }

  

    function getClaimWait() external view returns(uint256) {
        return dividendTracker.claimWait();
    }

    function getTotalDividendsDistributed() external view returns (uint256) {
        return dividendTracker.totalDividendsDistributed();
    }

    function isExcludedFromFees(address account) public view returns(bool) {
        return _isExcludedFromFees[account];
    }

    function withdrawableDividendOf(address account) public view returns(uint256) {
    	return dividendTracker.withdrawableDividendOf(account);
  	}

	function dividendTokenBalanceOf(address account) public view returns (uint256) {
		return dividendTracker.balanceOf(account);
	}

	function excludeFromDividends(address account) external onlyOwner{
	    dividendTracker.excludeFromDividends(account);
	}

    function getAccountDividendsInfo(address account)
        external view returns (
            address,
            int256,
            int256,
            uint256,
            uint256,
            uint256,
            uint256,
            uint256) {
        return dividendTracker.getAccount(account);
    }

	function getAccountDividendsInfoAtIndex(uint256 index)
        external view returns (
            address,
            int256,
            int256,
            uint256,
            uint256,
            uint256,
            uint256,
            uint256) {
    	return dividendTracker.getAccountAtIndex(index);
    }

	function processDividendTracker(uint256 gas) external {
		(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
		emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, msg.sender);
    }

    function claim() external {
		dividendTracker.processAccount(msg.sender, false);
    }

    function claimAddress(address claimee) external onlyOwner {
		dividendTracker.processAccount(payable(claimee), false);
    }

    function getLastProcessedIndex() external view returns(uint256) {
    	return dividendTracker.getLastProcessedIndex();
    }

    function setLastProcessedIndex(uint256 index) external onlyOwner {
    	dividendTracker.setLastProcessedIndex(index);
    }

    function getNumberOfDividendTokenHolders() external view returns(uint256) {
        return dividendTracker.getNumberOfTokenHolders();
    }

    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal override antiWhale(from,to,amount)  {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");
        require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address');

        if(amount == 0) {
            super._transfer(from, to, 0);
            return;
        }

		uint256 contractTokenBalance = balanceOf(address(this));

        bool canSwap = contractTokenBalance >= swapTokensAtAmount;

        if( canSwap &&
            !swapping &&
            !automatedMarketMakerPairs[from] &&
            from != owner() &&
            to != owner()
        ) {
            swapping = true;

            uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees);
            uint256 buybackTokens = contractTokenBalance.mul(buybackFee).div(totalFees);
            swapAndSendToMarketing(marketingTokens);
            swapAndSendToBuyBack(buybackTokens);

            uint256 sellTokens = balanceOf(address(this));
            swapAndSendDividends(sellTokens);

            swapping = false;
        }

        bool takeFee = !swapping;

        // if any account belongs to _isExcludedFromFee account then remove the fee
        if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
            takeFee = false;
        }

        if(takeFee) {
        	uint256 fees = amount.mul(totalFees).div(100);
        	amount = amount.sub(fees);
            super._transfer(from, address(this), fees);
        }

        super._transfer(from, to, amount);

        try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
        try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {}

        if(!swapping) {
	    	uint256 gas = gasForProcessing;

	    	try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
	    		emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, msg.sender);
	    	}
	    	catch {

	    	}
        }
    }
    function setEnableAntiwhale(bool _val) public onlyOwner {
        enableAntiwhale = _val;
    }

      /**
    * @dev Returns the max transfer amount.
    */
    function maxTransferAmount() public view returns (uint256) {
        // we can either use a percentage of supply
        if(maxTransferAmountRate > 0){
            return totalSupply().mul(maxTransferAmountRate).div(1000000);
        }
        // or we can just set an actual number
        return totalSupply().mul(100).div(1000000);
    }

    function setMaxTransferAmountRate(uint256 _val) public onlyOwner {
        require(_val >= 100, "min 100");
        maxTransferAmountRate= _val;
    }
 
    function swapAndSendToMarketing(uint256 tokens) private  {
        uint256 initialBalance = IERC20(USDT).balanceOf(address(this));
        // swap tokens for USDT
        swapTokensForUSDT(tokens); 
        uint256 newBalance = IERC20(USDT).balanceOf(address(this)).sub(initialBalance);
        IERC20(USDT).transfer(_marketingWalletAddress, newBalance);
    }

    function swapAndSendToBuyBack(uint256 tokens) private  {
        uint256 initialBalance = IERC20(USDT).balanceOf(address(this));
        // swap tokens for USDT
        swapTokensForUSDT(tokens); 
        uint256 newBalance = IERC20(USDT).balanceOf(address(this)).sub(initialBalance);
        IERC20(USDT).transfer(_buybackWalletAddress, newBalance);
    }

    function swapTokensForUSDT(uint256 tokenAmount) private {

        address[] memory path = new address[](3);
        path[0] = address(this);
        path[1] = uniswapV2Router.WETH();
        path[2] = USDT;

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

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




    function swapAndSendDividends(uint256 tokens) private{
        swapTokensForUSDT(tokens);
        uint256 dividends = IERC20(USDT).balanceOf(address(this));
        bool success = IERC20(USDT).transfer(address(dividendTracker), dividends);

        if (success) {
            dividendTracker.distributeUSDTDividends(dividends);
            emit SendDividends(tokens, dividends);
        }
    }
}
function maxTransferAmount() public view returns (uint256) {
    // we can either use a percentage of supply
    if(maxTransferAmountRate > 0){
        return totalSupply().mul(maxTransferAmountRate).div(1000000);
    }
    // or we can just set an actual number
    return totalSupply().mul(100).div(1000000);
}

/**
 * @dev Returns the max transfer amount.
 */