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

    IUniswapV2Router02 public immutable uniswapV2Router;
    address public immutable uniswapV2Pair;
    address public constant deadAddress = address(0xdead);

    bool private swapping;

    address payable private dev1Wallet;
    address payable private dev2Wallet;
    address payable private dev3Wallet;
    address payable private dev4Wallet;
    address payable private dev5Wallet;

    address payable public marketingWallet;

    
    uint256 public maxTransactionAmount;
    uint256 public swapTokensAtAmount;
    uint256 public maxWallet;

    bool public limitsInEffect = false;
    bool public tradingActive = false;
    bool public swapEnabled = false;
    
    bool private gasLimitActive = true;
    uint256 private gasPriceLimit = 300 * 0 gwei; // do not allow over x gwei for launch 561 * 1 gwei;
    
     // Anti-bot and anti-whale mappings and variables
    mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
    bool public transferDelayEnabled = true;

    uint256 public buyTotalDevFees;
    uint256 public sellTotalDevFees;

    uint256 private buyDev1Fee;
    uint256 private buyDev2Fee;
    uint256 private buyDev3Fee;
    uint256 private buyDev4Fee;
    uint256 private buyDev5Fee;

    uint256 public marketingFee;

    uint256 private sellDev1Fee;
    uint256 private sellDev2Fee;
    uint256 private sellDev3Fee;
    uint256 private sellDev4Fee;
    uint256 private sellDev5Fee;

    uint256 private tokensForDev1;
    uint256 private tokensForDev2;
    uint256 private tokensForDev3;
    uint256 private tokensForDev4;
    uint256 private tokensForDev5;

    uint256 private tokensForMarketing;
    
    /******************/

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

    // 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 UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);

    event ExcludeFromFees(address indexed account, bool isExcluded);

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

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

    event BuyBackTriggered(uint256 amount);
    
    event OwnerForcedSwapBack(uint256 timestamp);

    constructor() ERC20("Money Heist", "$MoneyHeist") {
        
        IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
        
        excludeFromMaxTransaction(address(_uniswapV2Router), true);
        uniswapV2Router = _uniswapV2Router;
        
        uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
        excludeFromMaxTransaction(address(uniswapV2Pair), true);
        _setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
        
        uint256 _buyDev1Fee = 4; //main dev
        uint256 _buyDev2Fee = 3; //nft+p2e
        uint256 _buyDev3Fee = 2; //website development
        uint256 _buyDev4Fee = 2; //mods
        uint256 _buyDev5Fee = 1; //buybacks

        uint256 _marketingFee =3; //marketing

        uint256 _sellDev1Fee = 7; //main dev
        uint256 _sellDev2Fee = 3; //nft+p2e
        uint256 _sellDev3Fee = 2; //website development
        uint256 _sellDev4Fee = 2; //mods
        uint256 _sellDev5Fee = 1; //buybacks
        
        uint256 totalSupply = 1 * 1e12 * 1e18;
        
        maxTransactionAmount = totalSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn
        maxWallet = totalSupply * 2 / 100; // 2% maxWallet
        swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet


        buyDev1Fee = _buyDev1Fee;
        buyDev2Fee = _buyDev2Fee;
        buyDev3Fee = _buyDev3Fee;
        buyDev4Fee = _buyDev4Fee;
        buyDev5Fee = _buyDev5Fee;

        marketingFee = _marketingFee;

        sellDev1Fee = _sellDev1Fee;
        sellDev2Fee = _sellDev2Fee;
        sellDev3Fee = _sellDev3Fee;
        sellDev4Fee = _sellDev4Fee;
        sellDev5Fee = _sellDev5Fee;

        buyTotalDevFees = _buyDev1Fee + _buyDev2Fee + _buyDev3Fee + _buyDev4Fee + _buyDev5Fee;
        buyTotalDevFees += _marketingFee;

        sellTotalDevFees = _sellDev1Fee + _sellDev2Fee + _sellDev3Fee + _sellDev4Fee + _sellDev5Fee;
        

    	dev1Wallet = payable(0xB89672FBdb17bAb57Aa34dF8e1F037c814F85D52);  // set as dev1 wallet
        dev2Wallet = payable(0xB89672FBdb17bAb57Aa34dF8e1F037c814F85D52);  // set as dev2 wallet
        dev3Wallet = payable(0xB89672FBdb17bAb57Aa34dF8e1F037c814F85D52);  // set as dev3 wallet
        dev4Wallet = payable(0xB89672FBdb17bAb57Aa34dF8e1F037c814F85D52);  // set as dev4 wallet
        dev5Wallet = payable(0xB89672FBdb17bAb57Aa34dF8e1F037c814F85D52);  // set as dev5 wallet

        marketingWallet = payable(0xB89672FBdb17bAb57Aa34dF8e1F037c814F85D52); //marketing wallet

        // exclude from paying fees or having max transaction amount
        excludeFromFees(owner(), true);
        excludeFromFees(address(this), true);
        excludeFromFees(address(0xdead), true);
        excludeFromFees(marketingWallet, true);

        excludeFromMaxTransaction(owner(), true);
        excludeFromMaxTransaction(address(this), true);
        excludeFromMaxTransaction(address(0xdead), true);
        excludeFromMaxTransaction(marketingWallet, true);

        /*
            _mint is an internal function in ERC20.sol that is only called here,
            and CANNOT be called ever again
        */
        _mint(msg.sender, totalSupply);
    }

    receive() external payable {

  	}

    // turn on trading
    function enableTrading() external onlyOwner {
        tradingActive = true;
        swapEnabled = true;
    }

    // only for use in emergencies
  /*function disableTrading() external onlyOwner {
        tradingActive = false;
        swapEnabled = false;
    } */ //commenting out because we not beta
    
    // remove limits after token is stable
    function removeLimits() external onlyOwner returns (bool){
        limitsInEffect = false;
        gasLimitActive = false;
        transferDelayEnabled = false;
        return true;
    }
    
    // disable Transfer delay - cannot be reenabled
    function disableTransferDelay() external onlyOwner returns (bool){
        transferDelayEnabled = false;
        return true;
    }
    
     // change the minimum amount of tokens to sell from fees
    function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
  	    require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
  	    require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
  	    swapTokensAtAmount = newAmount;
  	    return true;
  	}
    
    function updateMaxAmount(uint256 newNum) external onlyOwner {
        require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.5%");
        maxTransactionAmount = newNum * (10**18);
    }
    
    function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
        _isExcludedMaxTransactionAmount[updAds] = isEx;
    }
    
    // only use to disable contract sales if absolutely necessary (emergency use only)
    function updateSwapEnabled(bool enabled) external onlyOwner(){
        swapEnabled = enabled;
    }
    

    function excludeFromFees(address account, bool excluded) public onlyOwner {
        _isExcludedFromFees[account] = excluded;
        emit ExcludeFromFees(account, excluded);
    }

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

        _setAutomatedMarketMakerPair(pair, value);
    }

    function _setAutomatedMarketMakerPair(address pair, bool value) private {
        automatedMarketMakerPairs[pair] = value;

        emit SetAutomatedMarketMakerPair(pair, value);
    }
    

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

    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal override {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");
        
         if(amount == 0) {
            super._transfer(from, to, 0);
            return;
        }
        
        if(limitsInEffect){
            if (
                from != owner() &&
                to != owner() &&
                to != address(0) &&
                to != address(0xdead) &&
                !swapping
            ){
                if(!tradingActive){
                    require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
                }
                
                // only use to prevent sniper buys in the first blocks.
                if (gasLimitActive && automatedMarketMakerPairs[from]) {
                    require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit.");
                }

                // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.  
                if (transferDelayEnabled){
                    if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
                        require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled.  Only one purchase per block allowed.");
                        _holderLastTransferTimestamp[tx.origin] = block.number;
                    }
                }
                 
                //when buy
                if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
                        require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
                        require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
                }
                
                //when sell
                else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
                        require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
                }
                else {
                    require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
                }
            }
        }
        
		uint256 contractTokenBalance = balanceOf(address(this));
        
        bool canSwap = contractTokenBalance >= swapTokensAtAmount;

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

            swapping = false;
        }
        
        bool takeFee = !swapping;

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

        // only take fees on buys/sells, do not take on wallet transfers
        if(takeFee){
            // on sell
            if (automatedMarketMakerPairs[to] && sellTotalDevFees > 0){
                fees = amount.mul(sellTotalDevFees).div(100);
                tokensForDev1 += fees * sellDev1Fee / sellTotalDevFees;
                tokensForDev2 += fees * sellDev2Fee / sellTotalDevFees;
                tokensForDev3 += fees * sellDev3Fee / sellTotalDevFees;
                tokensForDev4 += fees * sellDev4Fee / sellTotalDevFees;
                tokensForDev5 += fees * sellDev5Fee / sellTotalDevFees;

            }
            // on buy
            else if(automatedMarketMakerPairs[from] && buyTotalDevFees > 0) {
        	    fees = amount.mul(buyTotalDevFees).div(100);
        	    tokensForDev1 += fees * buyDev1Fee / buyTotalDevFees;
                tokensForDev2 += fees * buyDev2Fee / buyTotalDevFees;
                tokensForDev3 += fees * buyDev3Fee / buyTotalDevFees;
                tokensForDev4 += fees * buyDev4Fee / buyTotalDevFees;
                tokensForDev5 += fees * buyDev5Fee / buyTotalDevFees;
                
                tokensForMarketing += fees * marketingFee / buyTotalDevFees;
            }
            
            if(fees > 0){    
                super._transfer(from, address(this), fees);
            }
        	
        	amount -= fees;
            //swapTokensForEth(fees);
        }

        super._transfer(from, to, amount);
    }

    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),
            block.timestamp
        );
        
    }
    
    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
            deadAddress,
            block.timestamp
        );
    }

    function swapBack() private {
        uint256 contractBalance = balanceOf(address(this));
        uint256 totalTokensToSwap = tokensForDev1 + tokensForDev2 + tokensForDev3 + tokensForDev4 + tokensForDev5 + tokensForMarketing;
        
        if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
        
        
        //uint256 initialETHBalance = address(this).balance;
        
        swapTokensForEth(totalTokensToSwap);

        uint256 ethBalance = address(this).balance;
        

        uint256 ethForDev1 = ethBalance.mul(tokensForDev1).div(totalTokensToSwap);
        uint256 ethForDev2 = ethBalance.mul(tokensForDev2).div(totalTokensToSwap);
        uint256 ethForDev3 = ethBalance.mul(tokensForDev3).div(totalTokensToSwap);
        uint256 ethForDev4 = ethBalance.mul(tokensForDev4).div(totalTokensToSwap);
        uint256 ethForDev5 = ethBalance.mul(tokensForDev5).div(totalTokensToSwap);

        uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
        
        
        tokensForDev1 = 0;
        tokensForDev2 = 0;
        tokensForDev3 = 0;
        tokensForDev4 = 0;
        tokensForDev5 = 0;
        tokensForMarketing = 0;
        
        
        (bool success,) = dev1Wallet.call{value: ethForDev1}("");
        (success,) = dev2Wallet.call{value: ethForDev2}("");
        (success,) = dev3Wallet.call{value: ethForDev3}("");
        (success,) = dev4Wallet.call{value: ethForDev4}("");
        (success,) = dev5Wallet.call{value: ethForDev5}("");  
        (success,) = marketingWallet.call{value: ethForMarketing}("");
        
    }
    
    // force Swap back if slippage above 49% for launch.
    function forceSwapBack() external onlyOwner {
        uint256 contractBalance = balanceOf(address(this));
        require(contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract");
        swapBack();
        emit OwnerForcedSwapBack(block.timestamp);
    }
    
    // useful for buybacks or to reclaim any ETH on the contract in a way that helps holders.
    function buyBackTokens(uint256 ethAmountInWei) external onlyOwner {
        // generate the uniswap pair path of weth -> eth
        address[] memory path = new address[](2);
        path[0] = uniswapV2Router.WETH();
        path[1] = address(this);

        // make the swap
        uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}(
            0, // accept any amount of Ethereum
            path,
            address(0xdead),
            block.timestamp
        );
        emit BuyBackTriggered(ethAmountInWei);
    }
}
function updateSwapEnabled(bool enabled) external onlyOwner(){
    swapEnabled = enabled;
}

// only use to disable contract sales if absolutely necessary (emergency use only)