contract Neko is ERC20('Neko', 'NEKO') {
    using SafeMath for uint256;
    uint256 public constant INITIAL_SUPPLY = 20000000000 * 1e18; // 20B

    uint16 public transferTaxRate = 200;    // Transfer tax rate in basis points (default 2%)

    address public marketingWalletAddress;
    // Addresses that excluded from antiWhale
    mapping(address => bool) private _excludedFromAntiWhale;
    // Addresses that excluded from transaction fee
    mapping(address => bool) private _excludedFromTransactionFee;
    
    IWETH public WETH;
    
    address[] public path;
    IUniRouter02 public uniswapRouter;
    uint256 slippageFactor = 950;   // 5% slippage as default
    uint256 MAX_SLIPPAGE_FACTOR = 990; // 1% slippage as minimum
    uint16 public maxTransferAmountRate = 50; // .5 % of total supply

    event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);

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

    constructor() public {
        _mint(msg.sender, INITIAL_SUPPLY);

        marketingWalletAddress = msg.sender;

        _excludedFromAntiWhale[msg.sender] = true;
        _excludedFromAntiWhale[address(0)] = true;
        _excludedFromAntiWhale[address(this)] = true;

        _excludedFromTransactionFee[msg.sender] = true;
        
        _moveDelegates(address(0), msg.sender, INITIAL_SUPPLY);
    }

    function isExcludedFromAntiwhale(address _user) external view returns (bool) {
        return _excludedFromAntiWhale[_user];
    }

    function isExcludedFromTransactionFee(address _user) external view returns (bool) {
        return _excludedFromTransactionFee[_user];
    }

    function maxTransferAmount() public view returns (uint256) {
        return totalSupply().mul(maxTransferAmountRate).div(10000);
    }

    function _transfer(address _sender, address _recepient, uint256 _amount) internal override antiWhale(_sender, _recepient, _amount) {
        if (transferTaxRate == 0 || _excludedFromTransactionFee[msg.sender]) {
            super._transfer(_sender, _recepient, _amount);
            _moveDelegates(_sender, _recepient, _amount);
        } else {
            uint256 taxAmount = _amount.mul(transferTaxRate).div(10000);
            uint256 sendAmount = _amount.sub(taxAmount);

            super._transfer(_sender, address(this), taxAmount);
            _moveDelegates(_sender, address(this), taxAmount);
            super._transfer(_sender, _recepient, sendAmount);
            _moveDelegates(_sender, _recepient, sendAmount);
        }
    }

    function withdrawFee() external onlyOwner {
        if (address(uniswapRouter) != address(0)) {
            uint256 _holdingAmount = IERC20(address(this)).balanceOf(address(this));
            if (_holdingAmount > 0) {
                uint256[] memory _amounts = uniswapRouter.getAmountsOut(_holdingAmount, path);
                uint256 _amountOut = _amounts[_amounts.length.sub(1)];
                uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
                    _holdingAmount,
                    _amountOut.mul(slippageFactor).div(1000),
                    path,
                    marketingWalletAddress,
                    block.timestamp.add(600)
                );
            }
        }
    }

    // update exclued address from anti whale. can be call by on the current operator
    function updateExcludedAddressFromAntiWhale(address _user, bool _isExcluded) external onlyOwner {
        _excludedFromAntiWhale[_user] = _isExcluded;
    }

    // update exclued address from tax fee. can be call by on the current operator
    function updateExcludedAddressFromTransactionFee(address _user, bool _isExcluded) external onlyOwner {
        _excludedFromTransactionFee[_user] = _isExcluded;
    }

    function updateMarketingWalletAddress(address _marketingWalletAddress) external onlyOwner {
        require(_marketingWalletAddress != address(0), "_marketingWalletAddress can not be zero address!");
      marketingWalletAddress = _marketingWalletAddress;
    }

    // pause tax fee strategy
    function pauseTaxStrategy() external onlyOwner {
        transferTaxRate = 0;
    }

    // unpause tax fee strategy
    function unpauseTaxStrategy() external onlyOwner {
        transferTaxRate = 200;
    }
    
    function updateTaxRate(uint16 _transferTaxRate) external onlyOwner {
        require(_transferTaxRate < 10000, '!transfer tax rate');
        transferTaxRate = _transferTaxRate;
    }

    mapping (address => address) internal _delegates;

    /// @notice A checkpoint for marking number of votes from a given block
    struct Checkpoint {
        uint32 fromBlock;
        uint256 votes;
    }

    /// @notice A record of votes checkpoints for each account, by index
    mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;

    /// @notice The number of checkpoints for each account
    mapping (address => uint32) public numCheckpoints;

    /// @notice The EIP-712 typehash for the contract's domain
    bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");

    /// @notice The EIP-712 typehash for the delegation struct used by the contract
    bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");

    /// @notice A record of states for signing / validating signatures
    mapping (address => uint) public nonces;

      /// @notice An event thats emitted when an account changes its delegate
    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);

    /// @notice An event thats emitted when a delegate account's vote balance changes
    event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);

    /**
     * @notice Gets the current votes balance for `account`
     * @param account The address to get votes balance
     * @return The number of current votes for `account`
     */
    function getCurrentVotes(address account)
        external
        view
        returns (uint256)
    {
        uint32 nCheckpoints = numCheckpoints[account];
        return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
    }

    /**
     * @notice Determine the prior number of votes for an account as of a block number
     * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
     * @param account The address of the account to check
     * @param blockNumber The block number to get the vote balance at
     * @return The number of votes the account had as of the given block
     */
    function getPriorVotes(address account, uint blockNumber)
        external
        view
        returns (uint256)
    {
        require(blockNumber < block.number, "SEA::getPriorVotes: not yet determined");

        uint32 nCheckpoints = numCheckpoints[account];
        if (nCheckpoints == 0) {
            return 0;
        }

        // First check most recent balance
        if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
            return checkpoints[account][nCheckpoints - 1].votes;
        }

        // Next check implicit zero balance
        if (checkpoints[account][0].fromBlock > blockNumber) {
            return 0;
        }

        uint32 lower = 0;
        uint32 upper = nCheckpoints - 1;
        while (upper > lower) {
            uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
            Checkpoint memory cp = checkpoints[account][center];
            if (cp.fromBlock == blockNumber) {
                return cp.votes;
            } else if (cp.fromBlock < blockNumber) {
                lower = center;
            } else {
                upper = center - 1;
            }
        }
        return checkpoints[account][lower].votes;
    }

    function _delegate(address delegator, address delegatee)
        internal
    {
        address currentDelegate = _delegates[delegator];
        uint256 delegatorBalance = balanceOf(delegator); // balance of underlying MARSs (not scaled);
        _delegates[delegator] = delegatee;

        emit DelegateChanged(delegator, currentDelegate, delegatee);

        _moveDelegates(currentDelegate, delegatee, delegatorBalance);
    }

    function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
        if (srcRep != dstRep && amount > 0) {
            if (srcRep != address(0)) {
                // decrease old representative
                uint32 srcRepNum = numCheckpoints[srcRep];
                uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
                uint256 srcRepNew = srcRepOld.sub(amount);
                _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
            }

            if (dstRep != address(0)) {
                // increase new representative
                uint32 dstRepNum = numCheckpoints[dstRep];
                uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
                uint256 dstRepNew = dstRepOld.add(amount);
                _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
            }
        }
    }

    function _writeCheckpoint(
        address delegatee,
        uint32 nCheckpoints,
        uint256 oldVotes,
        uint256 newVotes
    )
        internal
    {
        uint32 blockNumber = safe32(block.number, "SEA::_writeCheckpoint: block number exceeds 32 bits");

        if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
            checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
        } else {
            checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
            numCheckpoints[delegatee] = nCheckpoints + 1;
        }

        emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
    }

    /**
     * @dev Update the max transfer amount rate.
     * Can only be called by the current operator.
     */
    function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyOwner {
        require(_maxTransferAmountRate <= 10000, "SEA::updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate.");
        emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate);
        maxTransferAmountRate = _maxTransferAmountRate;
    }
    
    function updateUniRouter(address _router) external onlyOwner {
        uniswapRouter = IUniRouter02(_router);
        WETH = IWETH(uniswapRouter.WETH());
        path = [address(this), address(WETH)];
        IERC20(address(this)).approve(address(uniswapRouter), ~uint256(0));
    }
    
    function updateSlippageFactor(uint256 _slippageFactor) external onlyOwner {
        require(_slippageFactor <= MAX_SLIPPAGE_FACTOR, '!slippage factor');
        slippageFactor = _slippageFactor;
    }

    function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
        require(n < 2**32, errorMessage);
        return uint32(n);
    }

    function getChainId() internal view returns (uint) {
        uint256 chainId;
        assembly { chainId := chainid() }
        return chainId;
    }
}
// DYNAToken with Governance.
function getCurrentVotes(address account)
    external
    view
    returns (uint256)
{
    uint32 nCheckpoints = numCheckpoints[account];
    return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}

/**
 * @notice Gets the current votes balance for `account`
 * @param account The address to get votes balance
 * @return The number of current votes for `account`
 */