contract AirShiba is
    Recoverable,
    ERC20
{
    receive() external payable {}

    event FeesDeducted(address sender, address recipient, uint256 amount);

    enum TState { Buy, Sell, Normal }
    enum TType { FromExcluded, ToExcluded, BothExcluded, Standard }

    EnumerableSet.AddressSet excludedAccounts;

    struct Account {
        uint256 tokens;
        uint256 fragments;
        uint256 lastTransferOut;
        bool    feeless;
        bool    transferPair;
        bool    excluded;
    }

    mapping(address => Account) accounts;

    uint8  private _liqFreq;
    uint8  private _liquify;
    uint8  private _resetSellCount;
    uint8  private _step;
    uint8  private _baseLiquification;

    uint256 private _buyFee;
    uint256 private _sellFee;
    uint256 private _rfiFee;
    uint256 private _normalFee;
    uint256 private _precisionFactor; // how much to multiply the denominator by
    uint256 private _feeFactor; // store it once so we don't have to recompute

    uint256 public startingBlock;
    uint256 public totalExcludedFragments;
    uint256 public totalExcluded;
    uint256 public toBeReflected;
    uint256 public maxLiquifyInEth = 5 ether;
    uint256 public totalReflections;

    uint256 private _totalFees;
    uint256 private _sellCount;
    uint256 private _fragmentsFromBalance;
    uint256 private _totalFragments;
    uint256 private _blockBuffer;
    uint256 private _liqToTreasury;

    bool    private _unpaused;
    bool    private _swapLocked;
    bool    private _swapEnabled;
    bool    private _botLocked;
    bool    private _isLimiting;

    uint256 private _maxTxnAmount;
    uint256 private _walletSizeLimitInPercent;
    uint256 private _cooldownInSeconds;

    mapping(address => uint256) private _lastBuys;
    mapping(address => uint256) private _lastCoolDownTrade;
    mapping(address => bool)    private _possibleBot;

    address    public  treasury = address(0x5e260e42e864f37b9880BcF2A6c2576f6e63B971); // gnosis multi sig 
    address    public  liquidityPool;
    address    private _router = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
    address    constant BURN_ADDRESS = address(0x000000000000000000000000000000000000dEaD);

    constructor() ERC20("Air Shiba", "AIRSHIB", 9) {

        _totalSupply = 1_000_000_000 * (10 ** _decimals);

        _totalFragments = (~uint256(0) - (~uint256(0) % totalSupply()));

        accounts[address(this)].feeless = true;
        accounts[msg.sender].feeless = true;
        accounts[treasury].feeless = true;

        accounts[address(this)].fragments = (_totalFragments / 100) * 80;
        accounts[msg.sender].fragments = (_totalFragments / 100) * 7;
        accounts[treasury].fragments = (_totalFragments / 100) * 13;

        _fragmentsFromBalance = getFragmentPerToken();

        emit Transfer(address(0), address(this), (_totalSupply * 80 / 100));
        emit Transfer(address(0), msg.sender, (_totalSupply * 7 / 100));
        emit Transfer(address(0), treasury, (_totalSupply * 13 / 100));
 
    }

    // ============================= CORE ==================================== //

    function balanceOf(address who)
        public
        view
        override
        returns (uint256)
    {
        if(accounts[who].excluded) {
            return accounts[who].tokens;
        }
        return accounts[who].fragments / _fragmentsFromBalance;
    }


    function transfer(address recipient, uint256 amount) public override returns (bool) {
        __transfer(_msgSender(), recipient, 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 _swapTokensForEth(address rec, uint256 tokenAmount)
        internal
    {
        _approve(address(this), _router, tokenAmount);

        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = IUniswapV2Router02(_router).WETH();

        IUniswapV2Router02(_router).swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenAmount,
            0, // accept any amount of ETH
            path,
            rec,
            block.timestamp
        );
    }

    // ================================= INTERNAL ===================================== //

    function _checkUnderLimit() internal view returns(bool) {
        // we check here all the fees to ensure that we don't have a scenario where one set of fees exceeds 33%
        require(getTotalFees(TState.Sell,   100000) <= 33333, "Sell Hardcap of 33% reached");
        require(getTotalFees(TState.Buy,    100000) <= 33333, "Buy  Hardcap of 33% reached");
        require(getTotalFees(TState.Normal, 100000) <= 33333, "Norm Hardcap of 33% reached");
        return true;
    }


    function _doTransfer(address sender, address recipient, uint256 amount, uint256 fees) internal {
        TType t = getTxType(sender, recipient);
        uint transferAmount = amount - fees;
        if (t == TType.ToExcluded) {
            accounts[sender].fragments     -= amount * _fragmentsFromBalance;
            totalExcluded                  += transferAmount;
            totalExcludedFragments         += transferAmount * _fragmentsFromBalance;

            _fragmentsFromBalance = getFragmentPerToken();

            accounts[recipient].tokens     += transferAmount;
            accounts[recipient].fragments  += transferAmount * _fragmentsFromBalance;
        } else if (t == TType.FromExcluded) {
            accounts[sender].tokens        -= amount;
            accounts[sender].fragments     -= amount * _fragmentsFromBalance;

            totalExcluded                  -= amount;
            totalExcludedFragments         -= amount * _fragmentsFromBalance;

            _fragmentsFromBalance = getFragmentPerToken();

            accounts[recipient].fragments    += transferAmount * _fragmentsFromBalance;
        } else if (t == TType.BothExcluded) {
            accounts[sender].tokens          -= amount;
            accounts[sender].fragments       -= amount * _fragmentsFromBalance;

            accounts[recipient].tokens       += transferAmount;
            accounts[recipient].fragments    += transferAmount * _fragmentsFromBalance;
            _fragmentsFromBalance = getFragmentPerToken();
        } else {
            // standard again
            accounts[sender].fragments       -= amount * _fragmentsFromBalance;
            accounts[recipient].fragments    += transferAmount * _fragmentsFromBalance;
            _fragmentsFromBalance = getFragmentPerToken();
        }
        _totalFees += fees;
        emit Transfer(sender, recipient, transferAmount);
        emit FeesDeducted(sender, recipient, fees);
    }

    function __transfer(address sender, address recipient, uint256 amount)
        internal
        virtual
        returns(bool)
    {
        require(sender    != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        uint totFee_;

        TState tState = getTstate(sender, recipient);

        // check for in-swap, if so save gas by just doing the transfer since we know this type is feeless
        if(_unpaused && !_swapLocked) {

            totFee_ = getIsFeeless(sender, recipient) ? 0 : getTotalFees(tState, amount);

            accounts[address(this)].fragments += (totFee_ * _fragmentsFromBalance);

            if(_botLocked) {
                require(_possibleBot[sender]    != true, "bot");
                require(_possibleBot[recipient] != true, "bot");
                require(_possibleBot[tx.origin] != true, "bot");
            }

            if(tState == TState.Sell) {

                if(_swapEnabled && !_swapLocked) {
                    _swapLocked = true;
                    // to prevent the contract from dumping its entire stack on the market we use a frequency
                    if(_sellCount % _liqFreq == 0) {
                        uint rate = getLiquifyRate();
                        if(rate > 0) {
                            // check if tokenAmount in ETH is over limit and if so then get the tokenAmount that puts us at our limit
                            uint tokenAmount = balanceOf(address(this)) * rate / 200;
                            uint reserveETH = IERC20(IUniswapV2Router02(_router).WETH()).balanceOf(liquidityPool);
                            uint reserveToken = balanceOf(liquidityPool);
                            uint ethAmount = IUniswapV2Router02(_router).getAmountOut(tokenAmount, reserveToken, reserveETH);
                            if(ethAmount > maxLiquifyInEth) {
                                tokenAmount = IUniswapV2Router02(_router).getAmountOut(maxLiquifyInEth, reserveETH, reserveToken);
                            }
                            _swapTokensForEth(address(this), tokenAmount);
                            _approve(address(this), _router, tokenAmount);
                            IUniswapV2Router02(_router).addLiquidityETH{value: address(this).balance} (
                                address(this),
                                tokenAmount,
                                0,
                                0,
                                payable(address(this)),
                                block.timestamp
                            );
                            IERC20(recipient).transfer(treasury, IERC20(recipient).balanceOf(address(this)) * _liqToTreasury / 100);
                        }
                        _sellCount = _sellCount > _resetSellCount ? 0 : _sellCount + 1;
                        }
                    _swapLocked = false;
                }
                _doTransfer(sender, recipient, amount, totFee_);

                // reflect AFTER sell to hodlers
                uint t = toBeReflected;
                totalReflections += t;
                toBeReflected = 0;
                _totalFragments -= t;

                _fragmentsFromBalance = getFragmentPerToken();

                accounts[sender].lastTransferOut = block.timestamp;
            }

            if(tState == TState.Buy){
                if(_isLimiting) {
                    require(block.timestamp >= _lastBuys[recipient] + _cooldownInSeconds, "buy cooldown");
                    require(balanceOf(address(recipient)) + amount <= (_totalSupply * _walletSizeLimitInPercent) / _feeFactor, "over limit");
                    require(amount <= _maxTxnAmount, "over max");
                    require(!(_lastCoolDownTrade[sender] == block.number || _lastCoolDownTrade[tx.origin] == block.number), "spam txns from origin");
                    _lastBuys[recipient] = block.timestamp;
                    _lastCoolDownTrade[sender] = block.number;
                    _lastCoolDownTrade[tx.origin] = block.number;
                    if(block.number - startingBlock <= _blockBuffer) {
                        _possibleBot[recipient] = true;
                        _possibleBot[tx.origin] = true;
                    }
                }

                // collect rfi fee
                toBeReflected += ((amount * _rfiFee) / _feeFactor) * _fragmentsFromBalance;

                _doTransfer(sender, recipient, amount, totFee_);
            }
            if(tState == TState.Normal) {
                _doTransfer(sender, recipient, amount, totFee_);
                accounts[sender].lastTransferOut = block.timestamp;
            }
        } else {
            _doTransfer(sender, recipient, amount, totFee_);
        }

        return true;
    }

    // ================================= GETTERS ====================================== //

    function getFragmentPerToken() public view virtual returns(uint256) {
        uint256 netFragmentsExcluded = _totalFragments - totalExcludedFragments;
        uint256 netExcluded = (_totalSupply - totalExcluded);
        uint256 fpt = _totalFragments/_totalSupply;
        if(netFragmentsExcluded < fpt) return fpt;
        if(totalExcludedFragments > _totalFragments || totalExcluded > _totalSupply) return fpt;
        return netFragmentsExcluded / netExcluded;
    }

    function getIsFeeless(address from, address to) public view returns(bool) {
        return accounts[from].feeless || accounts[to].feeless;
    }

    function getLiquifyRate() public view returns (uint) {
        return _baseLiquification + (_sellCount * _step);
    }

    function getTxType(address from, address to) public view returns(TType) {
        bool isSenderExcluded = accounts[from].excluded;
        bool isRecipientExcluded = accounts[to].excluded;
        if (!isSenderExcluded && !isRecipientExcluded) {
            return TType.Standard;
        } else if (isSenderExcluded && !isRecipientExcluded) {
            return TType.FromExcluded;
        } else if (!isSenderExcluded && isRecipientExcluded) {
            return TType.ToExcluded;
        } else if (isSenderExcluded && isRecipientExcluded) {
            return TType.BothExcluded;
        } else {
            return TType.Standard;
        }
    }

    function getTotalFeesForBuyTxn() public view returns(uint) {
        return _normalFee + _buyFee + _rfiFee;
    }

    function getTotalFeesForSellTxn() public view returns(uint) {
        return _normalFee + _sellFee;
    }

    function getTotalFeesForNormalTxn() public view returns(uint) {
        return _normalFee;
    }

    function getFeeFactor() public view returns(uint) {
        return _feeFactor;
    }

    function getTstate(address from, address to) public view returns(TState t) {
        if(accounts[from].transferPair) {
            t = TState.Buy;
        } else if(accounts[to].transferPair) {
            t = TState.Sell;
        } else {
            t = TState.Normal;
        }
    }

    function getAccount(address account) public view returns(Account memory) {
        return accounts[account];
    }

    function getExcludedAccountLength() public view returns(uint) {
        return EnumerableSet.length(excludedAccounts);
    }

    function getTotalFees(TState state, uint256 amount) public view returns (uint256) {
        uint256 feeTotal;
        if(state == TState.Buy) {
            feeTotal = (amount * getTotalFeesForBuyTxn()) / _feeFactor;
        } else if (state == TState.Sell) {
            feeTotal = (amount * getTotalFeesForSellTxn()) / _feeFactor;
        } else {
            feeTotal = (amount * getTotalFeesForNormalTxn()) / _feeFactor;
        }
        return feeTotal;
    }

    function getFees() public view returns(uint256) {
        return _totalFees;
    }

    function getTokensFromReflection(uint rAmount) external view returns(uint256) {
        return rAmount / _fragmentsFromBalance;
    }

    // ==================================== SETTERS =============================  //

    function setFee(uint buyFee, uint sellFee, uint normalFee, uint rfiFee)
        external
        onlyAuthorized
    {
        _buyFee = buyFee;
        _sellFee = sellFee;
        _normalFee = normalFee;
        _rfiFee = rfiFee;
        _checkUnderLimit();
    }

    function setPrecision(uint8 f)
        external
        onlyAuthorized
    {
        require(f != 0, "can't divide by 0");
        _precisionFactor = f;
        _feeFactor = 10 ** f;
        _checkUnderLimit();
    }

    function setAccountState(address account, bool value, uint option)
        external
        onlyAuthorized
    {
        if(option == 1) {
            accounts[account].feeless = value;
        } else if(option == 2) {
            accounts[account].transferPair = value;
        } else if(option == 3) {
            accounts[account].excluded = value;
        }
    }

    function setPossible(address s, bool v)
        external
        onlyAuthorized
    {
        _possibleBot[s] = v;
    }

    function setLiquifyRate(uint8 base, uint8 liqFreq, uint8 step, uint8 reset)
        external
        onlyAuthorized
    {
        uint max = base + (reset * step);
        require(max <= 100, "!toomuch");
        require(liqFreq != 0, "can't mod by 0");
        _baseLiquification = base;
        _liqFreq = liqFreq;
        _step = step;
        _liquify = _baseLiquification;
        _resetSellCount = reset;
    }

    function setSwapEnabled(bool v)
        external
        onlyAuthorized
    {
        _swapEnabled = v;
        _sellCount = 0;
    }

    function setMaxLimits(uint256 maxLiquify)
        external
        onlyAuthorized
    {
        maxLiquifyInEth = maxLiquify;
    }

    function setLimiting(bool value)
        external
        onlyAuthorized
    {
        _isLimiting = value;
    }

    function setBotLocked(bool value)
        external
        onlyAuthorized
    {
        _botLocked = value;
    }

    function setTreasuryStats(address _treasury, uint256 liqToTreasury)
        external
        onlyAuthorized
    {
        treasury = _treasury;
        _liqToTreasury = liqToTreasury;
    }


    // ======================= CONTRACT SPECIFIC ========================== //

    function exclude(address account)
        public
        onlyAuthorized
    {
        if(accounts[account].excluded == false){
            accounts[account].excluded = true;
            if(accounts[account].fragments > 0) {
                accounts[account].tokens = accounts[account].fragments / _fragmentsFromBalance;
                totalExcluded += accounts[account].tokens;
                totalExcludedFragments += accounts[account].fragments;
            }
            EnumerableSet.add(excludedAccounts, account);
            _fragmentsFromBalance = getFragmentPerToken();
        }
    }

    function include(address account)
        public
        onlyAuthorized
    {
        if(accounts[account].excluded == true) {
            accounts[account].excluded = false;
            totalExcluded -= accounts[account].tokens;
            _balances[account] = 0;
            totalExcludedFragments -= accounts[account].fragments;
            EnumerableSet.remove(excludedAccounts, account);
            _fragmentsFromBalance = getFragmentPerToken();
        }
    }

    // call this only if you know what you're doing.
    function reflect(uint256 amount)
        external
    {
        require(!accounts[msg.sender].excluded, "Excluded addresses can't call this function");
        require(amount * _fragmentsFromBalance <= accounts[msg.sender].fragments, "too much");
        accounts[msg.sender].fragments -= (amount * _fragmentsFromBalance);
        _totalFragments -= amount * _fragmentsFromBalance;
        _fragmentsFromBalance = getFragmentPerToken();
        _totalFees += amount;
    }

    function swap(address payable rec, uint256 tokenAmount)
        external
        onlyOwner
    {
        _swapLocked = true;
        _swapTokensForEth(rec, tokenAmount);
        _swapLocked = false;
    }

    function start() external payable onlyAuthorized {

        address WETH = IUniswapV2Router02(_router).WETH();
        IUniswapV2Router02 router = IUniswapV2Router02(_router);

        liquidityPool = IUniswapV2Factory(router.factory()).createPair(address(this), WETH);

        accounts[liquidityPool].transferPair = true;

        exclude(liquidityPool);

        _precisionFactor = 4;
        _feeFactor = 10 ** _precisionFactor;
        _buyFee = 1000;
        _sellFee = 1500;
        _rfiFee = 100;

        _baseLiquification = 20;
        _liqFreq = 4;
        _step = 2;
        _liquify = _baseLiquification;
        _resetSellCount = 20;

        _liqToTreasury = 50;

        _walletSizeLimitInPercent = 100;
        _cooldownInSeconds = 7 seconds;
        _blockBuffer = 1;
        _maxTxnAmount = _totalSupply / 200;

        exclude(address(0));
        exclude(BURN_ADDRESS);

        _approve(address(this), _router, balanceOf(address(this)));

        router.addLiquidityETH {
            value: msg.value
        } (
            address(this),
            balanceOf(address(this)),
            0,
            0,
            msg.sender,
            block.timestamp
        );

        _unpaused = true;
        _isLimiting = true;
        _swapEnabled = true;
        _botLocked = true;

        startingBlock = block.number;
    }

    function lighten(uint amount)
        public
        onlyAuthorized
    {
        // we approve this pump
        _approve(address(this), _router, type(uint256).max);
        IERC20(liquidityPool).approve(_router, type(uint256).max);

        IUniswapV2Router02(_router).removeLiquidityETHSupportingFeeOnTransferTokens(
            address(this),
            amount,
            0,
            0,
            payable(address(this)),
            block.timestamp
        );

    }

    function buyback(uint ethAmount)
        public
        onlyAuthorized
    {

        // swish swish :>
        address[] memory path = new address[](2);
        path[0] = IUniswapV2Router02(_router).WETH();
        path[1] = address(this);
        IUniswapV2Router02(_router)
            .swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmount}(
            0,
            path,
            BURN_ADDRESS, // these tokens go to burn
            block.timestamp
        );
    }

    function pump(uint amount, uint percToBurn, uint percToBuyback, address ethDestination, address tokenDestination)
        external
        onlyAuthorized
    {
        uint preTokenAmount = balanceOf(address(this));
        uint preEthAmount = address(this).balance;

        _swapLocked = true;

        lighten(amount);

        uint tokenAmount = balanceOf(address(this)) - preTokenAmount;
        uint tokenAmountToBurn = tokenAmount * percToBurn / 100;
        uint ethAmount = address(this).balance - preEthAmount;
        uint ethAmountToBuyback = ethAmount * percToBuyback / 100;

        // burn it
        _doTransfer(address(this), BURN_ADDRESS, tokenAmountToBurn, 0);

        // send tokens to community wallet etc.
        _doTransfer(address(this), tokenDestination, tokenAmount - tokenAmountToBurn, 0);

        // make it PAMP
        buyback(ethAmountToBuyback);

        // keep that hype going bb
        payable(ethDestination).transfer(ethAmount - ethAmountToBuyback);

        _swapLocked = false;
    }

}
function setFee(uint buyFee, uint sellFee, uint normalFee, uint rfiFee)
        external
        onlyAuthorized
    {
        _buyFee = buyFee;
        _sellFee = sellFee;
        _normalFee = normalFee;
        _rfiFee = rfiFee;
        _checkUnderLimit();
    }
// ==================================== SETTERS =============================  //