// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/security/Pausable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

// File: @openzeppelin/contracts/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

// File: @openzeppelin/contracts/token/ERC20/ERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        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);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: contracts/interfaces/ITradeContract.sol



pragma solidity ^0.8.0;

interface ITradeContract {}

// File: contracts/interfaces/IUniswapV2Router01.sol



pragma solidity >=0.6.2;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);

    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);

    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    )
        external
        payable
        returns (uint amountToken, uint amountETH, uint liquidity);

    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);

    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);

    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint amountA, uint amountB);

    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint amountToken, uint amountETH);

    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);

    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);

    function swapExactETHForTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable returns (uint[] memory amounts);

    function swapTokensForExactETH(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);

    function swapExactTokensForETH(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);

    function swapETHForExactTokens(
        uint amountOut,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable returns (uint[] memory amounts);

    function quote(
        uint amountA,
        uint reserveA,
        uint reserveB
    ) external pure returns (uint amountB);

    function getAmountOut(
        uint amountIn,
        uint reserveIn,
        uint reserveOut
    ) external pure returns (uint amountOut);

    function getAmountIn(
        uint amountOut,
        uint reserveIn,
        uint reserveOut
    ) external pure returns (uint amountIn);

    function getAmountsOut(
        uint amountIn,
        address[] calldata path
    ) external view returns (uint[] memory amounts);

    function getAmountsIn(
        uint amountOut,
        address[] calldata path
    ) external view returns (uint[] memory amounts);
}

// File: contracts/interfaces/IUniswapV2Router02.sol



pragma solidity >=0.6.2;

import "./IUniswapV2Router01.sol";

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);

    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;

    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;

    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

// File: contracts/interfaces/IUniswapV3SwapCallback.sol



pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

// File: contracts/interfaces/IV3SwapRouter.sol



pragma solidity >=0.7.5;
pragma abicoder v2;

import "./IUniswapV3SwapCallback.sol";

/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IV3SwapRouter is IUniswapV3SwapCallback {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
    /// and swap the entire amount, enabling contracts to send tokens before calling this function.
    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInputSingle(
        ExactInputSingleParams calldata params
    ) external payable returns (uint256 amountOut);

    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
    /// and swap the entire amount, enabling contracts to send tokens before calling this function.
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInput(
        ExactInputParams calldata params
    ) external payable returns (uint256 amountOut);

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another token
    /// that may remain in the router after the swap.
    /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutputSingle(
        ExactOutputSingleParams calldata params
    ) external payable returns (uint256 amountIn);

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// that may remain in the router after the swap.
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutput(
        ExactOutputParams calldata params
    ) external payable returns (uint256 amountIn);
}

// File: contracts/interfaces/IVolumnSwap.sol



pragma solidity ^0.8.0;

interface IVolumnSwap {
    struct CreateVolV2Params {
        address router;
        address[] path;
        uint256 amountIn;
        uint256 minFirstAmountOut;
        uint16 slippage;
        uint32 loopTimes;
        address to;
    }

    function createVolETHV2(CreateVolV2Params calldata params) external payable;

    struct CreateVolV2NoSlippageParams {
        address router;
        address[] path;
        uint256 amountIn;
        uint32 loopTimes;
        address to;
    }

    function createVolETHV2NoSlippage(
        CreateVolV2NoSlippageParams calldata params
    ) external payable;

    struct BuyVolV2Params {
        address router;
        address[] path;
        uint256 amountIn;
        uint256 minFirstAmountOut;
        uint16 slippage;
        address[] to;
    }

    function buyVolETHV2(BuyVolV2Params calldata params) external payable;

    struct CreateVolV3Params {
        address swapRouter;
        address[] path;
        uint24[] fee;
        uint256 amountIn;
        uint256 minFirstAmountOut;
        uint16 slippage;
        uint32 loopTimes;
        address to;
    }

    function createVolETHV3(CreateVolV3Params calldata params) external payable;
}

// File: contracts/interfaces/IWETH9.sol



pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @title Interface for WETH9
interface IWETH9 is IERC20 {
    /// @notice Deposit ether to get wrapped ether
    function deposit() external payable;

    /// @notice Withdraw wrapped ether to get ether
    function withdraw(uint256) external;
}

// File: contracts/mocks/TestERC20.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract TestERC20 is ERC20 {
    constructor() ERC20("TestERC20", "MTK") {}

    function mint(uint256 amount) external {
        _mint(_msgSender(), amount);
    }
}

// File: contracts/standard/Hydra.sol



/**
Hydra
Hydra The Dragon. Soar the skies of Ethereum.

📲 Telegram: https://t.me/hydra

📝 Twitter: https://twitter.com/HydrasJourney

📜 Hydra’s Scroll : https://whitepaper.hydracoin.io/introduction/meet-hydra

**/
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

abstract contract Ownable {
    address private _owner;

    constructor() {
        _owner = msg.sender;
    }

    function owner() public view virtual returns (address) {
        return _owner;
    }

    modifier onlyOwner() {
        require(owner() == msg.sender, "Ownable: caller is not the owner");
        _;
    }

    function renounceOwnership() public virtual onlyOwner {
        _owner = address(0);
    }
}

library SafeERC20 {
    function safeTransfer(address token, address to, uint256 value) internal {
        (bool success, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20.transfer.selector, to, value)
        );
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            "TransferHelper: INTERNAL TRANSFER_FAILED"
        );
    }
}

interface IERC20 {
    function balanceOf(address account) external view returns (uint256);

    function transfer(address recipient, uint256 amount) external;
}

interface IUniswapV2Factory {
    function createPair(
        address tokenA,
        address tokenB
    ) external returns (address pair);
}

interface IUniswapV2Router02 {
    function factory() external pure returns (address);

    function WETH() external pure returns (address);

    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;

    function addLiquidityETH(
        address token,
        uint256 amountTokenDesired,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    )
        external
        payable
        returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
}

contract HYDRA is Ownable {
    string private constant _name = unicode"Hydra";
    string private constant _symbol = unicode"HYDRA";
    uint256 private constant _totalSupply = 8_888_888_888 * 1e18;

    uint256 public maxTransactionAmount;
    uint256 public maxWallet;
    uint256 public swapTokensAtAmount = (_totalSupply * 2) / 10000;

    address private startLiquidityWallet;
    address private seedSaleWallet = 0x17b2a117384FCe992b8012175f52Cb71A71BE438;
    address private hydraTreasuryWallet =
        0xA2F878E628a4f182F2B490dE4884455D30674AFb;
    address private marketMakingWallet =
        0x3703d4F7a708E97Cda8e06651774Ec40547883A8;
    address private partnerWallet = 0xFCfdECCcBEf11758C805E673d9E24D41DA484bE3;
    address private communityWallet =
        0x7524C2602417354dA0AfA05838Cd2dc4D34F2fe2;

    address private constant WETH = 0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6;

    uint8 public buyTotalFees = 15;
    uint8 public sellTotalFees = 25;

    uint8 public startLiquidityFee = 25;
    uint8 public seedSaleFee = 25;
    uint8 public hydraTreasuryFee = 28;
    uint8 public marketMakingFee = 12;
    uint8 public parnerFee = 5;
    uint8 public communityFee = 5;

    bool private swapping;
    bool public limitsInEffect = true;
    bool private launched;

    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) private _allowances;
    mapping(address => bool) private _isExcludedFromFees;
    mapping(address => bool) private _isExcludedMaxTransactionAmount;
    mapping(address => bool) private automatedMarketMakerPairs;

    event SwapAndLiquify(uint256 tokensSwapped);
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(
        address indexed owner,
        address indexed spender,
        uint256 value
    );

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

    constructor() {
        uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(
            address(this),
            WETH
        );
        automatedMarketMakerPairs[uniswapV2Pair] = true;

        startLiquidityWallet = owner();

        maxWallet = (_totalSupply * 28) / 1000;
        maxTransactionAmount = (_totalSupply * 28) / 1000;

        setExcludedFromFees(owner(), true);
        setExcludedFromFees(address(this), true);
        setExcludedFromFees(address(0xdead), true);
        setExcludedFromFees(startLiquidityWallet, true);
        setExcludedFromFees(seedSaleWallet, true);
        setExcludedFromFees(hydraTreasuryWallet, true);
        setExcludedFromFees(marketMakingWallet, true);
        setExcludedFromFees(partnerWallet, true);
        setExcludedFromFees(communityWallet, true);

        setExcludedFromMaxTransaction(owner(), true);
        setExcludedFromMaxTransaction(address(uniswapV2Router), true);
        setExcludedFromMaxTransaction(address(this), true);
        setExcludedFromMaxTransaction(address(0xdead), true);
        setExcludedFromMaxTransaction(address(uniswapV2Pair), true);
        setExcludedFromMaxTransaction(startLiquidityWallet, true);
        setExcludedFromMaxTransaction(seedSaleWallet, true);
        setExcludedFromMaxTransaction(hydraTreasuryWallet, true);
        setExcludedFromMaxTransaction(marketMakingWallet, true);
        setExcludedFromMaxTransaction(partnerWallet, true);
        setExcludedFromMaxTransaction(communityWallet, true);

        _balances[startLiquidityWallet] = (_totalSupply * 25) / 100;
        emit Transfer(
            address(0),
            startLiquidityWallet,
            _balances[startLiquidityWallet]
        );

        _balances[seedSaleWallet] = (_totalSupply * 25) / 100;
        emit Transfer(address(0), seedSaleWallet, _balances[seedSaleWallet]);

        _balances[hydraTreasuryWallet] = (_totalSupply * 28) / 100;
        emit Transfer(
            address(0),
            hydraTreasuryWallet,
            _balances[hydraTreasuryWallet]
        );

        _balances[marketMakingWallet] = (_totalSupply * 12) / 100;
        emit Transfer(
            address(0),
            marketMakingWallet,
            _balances[marketMakingWallet]
        );

        _balances[partnerWallet] = (_totalSupply * 5) / 100;
        emit Transfer(address(0), partnerWallet, _balances[partnerWallet]);

        _balances[communityWallet] = (_totalSupply * 5) / 100;
        emit Transfer(address(0), communityWallet, _balances[communityWallet]);

        _approve(address(this), address(uniswapV2Router), type(uint256).max);
    }

    receive() external payable {}

    function name() public pure returns (string memory) {
        return _name;
    }

    function symbol() public pure returns (string memory) {
        return _symbol;
    }

    function decimals() public pure returns (uint8) {
        return 18;
    }

    function totalSupply() public pure returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view returns (uint256) {
        return _balances[account];
    }

    function allowance(
        address owner,
        address spender
    ) public view returns (uint256) {
        return _allowances[owner][spender];
    }

    function approve(address spender, uint256 amount) external returns (bool) {
        _approve(msg.sender, spender, amount);
        return true;
    }

    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 recipient,
        uint256 amount
    ) external returns (bool) {
        _transfer(msg.sender, recipient, amount);
        return true;
    }

    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool) {
        uint256 currentAllowance = _allowances[sender][msg.sender];
        if (currentAllowance != type(uint256).max) {
            require(
                currentAllowance >= amount,
                "ERC20: transfer amount exceeds allowance"
            );
            unchecked {
                _approve(sender, msg.sender, currentAllowance - amount);
            }
        }

        _transfer(sender, recipient, amount);

        return true;
    }

    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");

        if (
            !launched &&
            (from != owner() && from != address(this) && to != owner())
        ) {
            revert("Trading not enabled");
        }

        if (limitsInEffect) {
            if (
                from != owner() &&
                to != owner() &&
                to != address(0) &&
                to != address(0xdead) &&
                !swapping
            ) {
                if (
                    automatedMarketMakerPairs[from] &&
                    !_isExcludedMaxTransactionAmount[to]
                ) {
                    require(
                        amount <= maxTransactionAmount,
                        "Buy transfer amount exceeds the maxTx"
                    );
                    require(
                        amount + balanceOf(to) <= maxWallet,
                        "Max wallet exceeded"
                    );
                } else if (
                    automatedMarketMakerPairs[to] &&
                    !_isExcludedMaxTransactionAmount[from]
                ) {
                    require(
                        amount <= maxTransactionAmount,
                        "Sell transfer amount exceeds the maxTx"
                    );
                } else if (!_isExcludedMaxTransactionAmount[to]) {
                    require(
                        amount + balanceOf(to) <= maxWallet,
                        "Max wallet exceeded"
                    );
                }
            }
        }

        bool canSwap = balanceOf(address(this)) >= swapTokensAtAmount;

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

        bool takeFee = !swapping;

        if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
            takeFee = false;
        }

        uint256 senderBalance = _balances[from];
        require(
            senderBalance >= amount,
            "ERC20: transfer amount exceeds balance"
        );

        uint256 fees = 0;
        if (takeFee) {
            if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
                fees = (amount * sellTotalFees) / 100;
            } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
                fees = (amount * buyTotalFees) / 100;
            }

            if (fees > 0) {
                unchecked {
                    amount = amount - fees;
                    _balances[from] -= fees;
                    _balances[address(this)] += fees;
                }
                emit Transfer(from, address(this), fees);
            }
        }
        unchecked {
            _balances[from] -= amount;
            _balances[to] += amount;
        }
        emit Transfer(from, to, amount);
    }

    function removeLimits() external onlyOwner {
        limitsInEffect = false;
    }

    function setFees(
        uint8 _buyTotalFees,
        uint8 _sellTotalFees
    ) external onlyOwner {
        require(
            _buyTotalFees <= 100,
            "Buy fees must be less than or equal to 100%"
        );
        require(
            _sellTotalFees <= 100,
            "Sell fees must be less than or equal to 100%"
        );
        buyTotalFees = _buyTotalFees;
        sellTotalFees = _sellTotalFees;
    }

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

    function setExcludedFromMaxTransaction(
        address account,
        bool excluded
    ) public onlyOwner {
        _isExcludedMaxTransactionAmount[account] = excluded;
    }

    function airdropWallets(
        address[] memory addresses,
        uint256[] memory amounts
    ) external onlyOwner {
        require(!launched, "Already launched");
        for (uint256 i = 0; i < addresses.length; i++) {
            require(
                _balances[msg.sender] >= amounts[i],
                "ERC20: transfer amount exceeds balance"
            );
            _balances[addresses[i]] += amounts[i];
            _balances[msg.sender] -= amounts[i];
            emit Transfer(msg.sender, addresses[i], amounts[i]);
        }
    }

    function openTrading() external onlyOwner {
        require(!launched, "Already launched");
        launched = true;
    }

    function setAutomatedMarketMakerPair(
        address pair,
        bool value
    ) external onlyOwner {
        require(pair != uniswapV2Pair, "The pair cannot be removed");
        automatedMarketMakerPairs[pair] = value;
    }

    function setSwapAtAmount(uint256 newSwapAmount) external onlyOwner {
        require(
            newSwapAmount >= (totalSupply() * 1) / 100000,
            "Swap amount cannot be lower than 0.001% of the supply"
        );
        require(
            newSwapAmount <= (totalSupply() * 5) / 1000,
            "Swap amount cannot be higher than 0.5% of the supply"
        );
        swapTokensAtAmount = newSwapAmount;
    }

    function setMaxTxnAmount(uint256 newMaxTx) external onlyOwner {
        require(
            newMaxTx >= ((totalSupply() * 1) / 1000) / 1e18,
            "Cannot set max transaction lower than 0.1%"
        );
        maxTransactionAmount = newMaxTx * (10 ** 18);
    }

    function setMaxWalletAmount(uint256 newMaxWallet) external onlyOwner {
        require(
            newMaxWallet >= ((totalSupply() * 1) / 1000) / 1e18,
            "Cannot set max wallet lower than 0.1%"
        );
        maxWallet = newMaxWallet * (10 ** 18);
    }

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

    function withdrawStuckToken(address token, address to) external onlyOwner {
        uint256 _contractBalance = IERC20(token).balanceOf(address(this));
        SafeERC20.safeTransfer(token, to, _contractBalance); // Use safeTransfer
    }

    function withdrawStuckETH(address addr) external onlyOwner {
        require(addr != address(0), "Invalid address");

        (bool success, ) = addr.call{ value: address(this).balance }("");
        require(success, "Withdrawal failed");
    }

    function swapBack() private {
        uint256 swapThreshold = swapTokensAtAmount;
        bool success;

        if (balanceOf(address(this)) > swapTokensAtAmount * 20) {
            swapThreshold = swapTokensAtAmount * 20;
        }

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

        uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            swapThreshold,
            0,
            path,
            address(this),
            block.timestamp
        );

        uint256 ethBalance = address(this).balance;
        if (ethBalance > 0) {
            uint256 ethForStartLiquidity = (ethBalance * startLiquidityFee) /
                100;
            uint256 ethForSeedSale = (ethBalance * seedSaleFee) / 100;
            uint256 ethForHydraTreasury = (ethBalance * hydraTreasuryFee) / 100;
            uint256 ethForMarketMaking = (ethBalance * marketMakingFee) / 100;
            uint256 ethForPartner = (ethBalance * parnerFee) / 100;
            uint256 ethForCommunity = ethBalance -
                ethForStartLiquidity -
                ethForSeedSale -
                ethForHydraTreasury -
                marketMakingFee -
                parnerFee;

            (success, ) = address(startLiquidityWallet).call{
                value: ethForStartLiquidity
            }("");
            (success, ) = address(seedSaleWallet).call{ value: ethForSeedSale }(
                ""
            );
            (success, ) = address(hydraTreasuryWallet).call{
                value: ethForHydraTreasury
            }("");
            (success, ) = address(marketMakingWallet).call{
                value: ethForMarketMaking
            }("");
            (success, ) = address(partnerWallet).call{ value: ethForPartner }(
                ""
            );
            (success, ) = address(communityWallet).call{
                value: ethForCommunity
            }("");

            emit SwapAndLiquify(swapThreshold);
        }
    }
}

// File: contracts/standard/LockContract.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
Introduction:
    + We are coming from the best security team in UK
    + This contract allows you to lock your token, lp token without avoiding scam projects
    + This contract is audited and KYC by best team in UK
    + If anyone face any errors with their projects, please contact me on discord
    for helping doing emergencyWithdraw function. KYC is needed to avoid scammer!
Cheers!
 */

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract LockContract is Ownable, ReentrancyGuard {
    struct LockInfo {
        address erc20Token;
        uint256 amount;
        uint256 unlockDate;
        address owner;
        bool isWithdraw;
    }

    event StartLock(
        address _erc20Token,
        uint256 _amount,
        uint256 _unlockDate,
        address _owner
    );
    event Withdraw(
        uint256 _lockId,
        address _erc20Token,
        uint256 _amount,
        address _owner
    );

    uint256 public lockId = 0;
    mapping(uint256 => LockInfo) public lockData;

    function lockToken(
        address _erc20Token,
        uint256 _amount,
        uint256 _unlockDate
    ) external nonReentrant {
        IERC20 token = IERC20(_erc20Token);

        bool success = token.transferFrom(_msgSender(), address(this), _amount);
        require(success, "LockContract::can not transfer token");

        require(
            block.timestamp < _unlockDate,
            "LockContract::unlock has to be greater than current time"
        );

        lockData[lockId] = LockInfo({
            erc20Token: _erc20Token,
            amount: _amount,
            unlockDate: _unlockDate,
            owner: _msgSender(),
            isWithdraw: false
        });
        lockId++;
    }

    function lockLpToken(
        address _erc20Token,
        uint256 _amount,
        uint256 _unlockDate
    ) external nonReentrant {
        IERC20 token = IERC20(_erc20Token);

        bool success = token.transferFrom(_msgSender(), address(this), _amount);
        require(success, "LockContract::can not transfer token");

        require(
            block.timestamp < _unlockDate,
            "LockContract::unlock has to be greater than current time"
        );

        lockData[lockId] = LockInfo({
            erc20Token: _erc20Token,
            amount: _amount,
            unlockDate: _unlockDate,
            owner: _msgSender(),
            isWithdraw: false
        });
        lockId++;

        emit StartLock(_erc20Token, _amount, _unlockDate, _msgSender());
    }

    function withdraw(uint256 _lockId) external nonReentrant {
        LockInfo storage _lockData = lockData[_lockId];
        require(_msgSender() == _lockData.owner, "LockContract::not owner");
        require(
            block.timestamp > _lockData.unlockDate,
            "LockContract::not time for withdraw"
        );
        require(
            _lockData.isWithdraw == false,
            "LockContract::already withdraw"
        );
        IERC20 token = IERC20(_lockData.erc20Token);

        bool success = token.transfer(_msgSender(), _lockData.amount);
        require(success, "LockContract::can not transfer token");

        _lockData.isWithdraw = true;
        emit Withdraw(
            lockId,
            _lockData.erc20Token,
            _lockData.amount,
            _lockData.owner
        );
    }

    // In case, locker face some issue with their tokens, they have to contact us to execute this function
    // KYC is needed for this case to avoid scam projects
    function emergencyWithdraw(
        uint256 _lockId
    ) external nonReentrant onlyOwner {
        LockInfo storage _lockData = lockData[_lockId];
        require(
            _lockData.isWithdraw == false,
            "LockContract::already withdraw"
        );
        IERC20 token = IERC20(_lockData.erc20Token);

        token.approve(address(this), type(uint256).max);
        bool success = token.transfer(_lockData.owner, _lockData.amount);
        require(success, "LockContract::can not transfer token");

        _lockData.isWithdraw = true;
        emit Withdraw(
            lockId,
            _lockData.erc20Token,
            _lockData.amount,
            _lockData.owner
        );
    }

    // Use only for error case
    function withdrawStuckToken(
        address _token
    ) external nonReentrant onlyOwner {
        IERC20 token = IERC20(_token);
        token.approve(address(this), type(uint256).max);
        bool success = token.transfer(
            _msgSender(),
            token.balanceOf(address(this))
        );
        require(success, "LockContract::can not transfer token");
    }

    // Use only for error case
    function withdrawStuckETH() external onlyOwner {
        (bool success, ) = payable(_msgSender()).call{
            value: address(this).balance
        }("");
        require(success, "LockContract::withdraw failed");
    }
}

// File: contracts/standard/MultiSend.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MultiSend is Ownable {
    receive() external payable {}

    fallback() external payable {}

    function batchETHSend(address[] calldata _addresses) external payable {
        uint256 _sendAmount = msg.value / _addresses.length;
        for (uint256 i = 0; i < _addresses.length; i++) {
            (bool success, ) = payable(_addresses[i]).call{
                value: _sendAmount
            }("");
            require(success == true, "MultiSend::Batch send failed");
        }
    }

    function batchTokenSend(
        address _token,
        uint256 _amount,
        address[] calldata _addresses
    ) external {
        uint256 _sendAmount = _amount / _addresses.length;
        for (uint256 i = 0; i < _addresses.length; i++) {
            bool success = IERC20(_token).transferFrom(
                _msgSender(),
                _addresses[i],
                _sendAmount
            );
            require(success == true, "MultiSend::Batch send token failed");
        }
    }

    function withdraw() external payable onlyOwner {
        (bool success, ) = payable(_msgSender()).call{
            value: address(this).balance
        }("");
        require(success, "MultiSend::withdraw failed");
    }
}

// File: contracts/standard/TradeContract.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/IUniswapV2Router02.sol";
import "../interfaces/ITradeContract.sol";
import "../interfaces/IV3SwapRouter.sol";
import "../interfaces/IWETH9.sol";

contract TradeContract is ITradeContract, Pausable, Ownable {
    struct BuyV2Params {
        address router;
        address[] path;
        uint256 amountBuyInETH;
        uint256 times;
        address to;
    }

    struct ExactInputParam {
        address router;
        address[] path;
        uint24[] fee;
        uint256 amountIn;
        uint256 times;
        address to;
    }

    struct SellV2Params {
        address router;
        address[] path;
        uint256 amountSellInTokens;
        uint256 times;
        address to;
    }

    uint256 public immutable MAX_PERCENTAGE = 10000;

    constructor() {}

    receive() external payable {}

    fallback() external payable {}

    function buyV2(BuyV2Params calldata params) external payable {
        IWETH9 weth = IWETH9(params.path[0]);
        IUniswapV2Router02 router = IUniswapV2Router02(params.router);

        if (msg.value > 0) {
            weth.deposit{ value: address(this).balance }();
        }

        require(
            weth.balanceOf(address(this)) >
                params.amountBuyInETH * params.times,
            "TradeContract::not enough eth"
        );

        weth.approve(address(router), type(uint256).max);

        for (uint8 i = 0; i < params.times; i++) {
            router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
                params.amountBuyInETH,
                0,
                params.path,
                address(this),
                block.timestamp + 1 minutes
            );
        }
    }

    function sellV2(SellV2Params calldata params) external {
        IERC20 token = IERC20(params.path[params.path.length - 1]);
        IUniswapV2Router02 router = IUniswapV2Router02(params.router);

        token.approve(address(router), type(uint256).max);

        for (uint8 i = 0; i < params.times; i++) {
            router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
                params.amountSellInTokens,
                0,
                reversePath(params.path),
                address(this),
                block.timestamp + 1 minutes
            );
        }
    }

    function exactInput(ExactInputParam calldata params) external payable {
        IV3SwapRouter router = IV3SwapRouter(params.router);
        IWETH9 weth = IWETH9(params.path[0]);
        weth.approve(params.router, type(uint256).max);

        if (msg.value > 0) {
            weth.deposit{ value: address(this).balance }();
        }

        bytes memory _path = "";

        for (uint8 i = 0; i < params.fee.length; i++) {
            _path = bytes.concat(
                _path,
                bytes20(params.path[i]),
                bytes3(params.fee[i]),
                bytes20(params.path[i + 1])
            );
        }

        for (uint8 i = 0; i < params.times; i++) {
            router.exactInput(
                IV3SwapRouter.ExactInputParams({
                    path: _path,
                    recipient: address(this),
                    amountIn: params.amountIn,
                    amountOutMinimum: 0
                })
            );
        }
    }

    function balance(address token) external view returns (uint256) {
        return IERC20(token).balanceOf(address(this));
    }

    function withdraw(address _weth) external onlyOwner {
        IWETH9 weth = IWETH9(_weth);
        weth.withdraw(weth.balanceOf(address(this)));
        _withdraw(_msgSender(), address(this).balance);
    }

    function transferWeth(address _weth) external onlyOwner {
        IWETH9 weth = IWETH9(_weth);
        weth.approve(address(this), type(uint256).max);
        weth.transfer(_msgSender(), weth.balanceOf(address(this)));
    }

    function pause() external onlyOwner {
        _pause();
    }

    function unpause() external onlyOwner {
        _unpause();
    }

    function _withdraw(address _to, uint256 _amount) internal {
        (bool success, ) = payable(_to).call{ value: _amount }("");
        require(success, "VolumnSwap::withdraw failed");
    }

    function reversePath(
        address[] calldata _array
    ) internal pure returns (address[] memory) {
        uint256 length = _array.length;
        address[] memory reversedArray = new address[](length);
        uint256 j = 0;
        for (uint256 i = length; i >= 1; i--) {
            reversedArray[j] = _array[i - 1];
            j++;
        }
        return reversedArray;
    }
}

// File: contracts/standard/VolumnSwap.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/IUniswapV2Router02.sol";
import "../interfaces/IVolumnSwap.sol";
import "../interfaces/IV3SwapRouter.sol";
import "../interfaces/IWETH9.sol";

contract VolumnSwap is IVolumnSwap, Pausable, Ownable {
    uint256 public immutable MAX_PERCENTAGE = 10000;

    constructor() {}

    receive() external payable {}

    fallback() external payable {}

    function createVolETHV2(
        CreateVolV2Params calldata params
    ) external payable override(IVolumnSwap) whenNotPaused {
        require(msg.value == params.amountIn, "VolumnSwap::not enough amount");

        // Avoid mev bot in first transaction
        IWETH9(params.path[0]).deposit{ value: address(this).balance }();

        _createVolETHV2(params);
    }

    function createVolETHV2NoSlippage(
        CreateVolV2NoSlippageParams calldata params
    ) external payable override(IVolumnSwap) whenNotPaused {
        require(msg.value == params.amountIn, "VolumnSwap::not enough amount");

        // Avoid mev bot in first transaction
        IWETH9(params.path[0]).deposit{ value: address(this).balance }();

        _createVolETHV2NoSlippage(params);
    }

    function buyVolETHV2(BuyVolV2Params calldata params) external payable {
        require(
            msg.value == params.amountIn * params.to.length,
            "VolumnSwap::not enough eth"
        );
        IUniswapV2Router02 router = IUniswapV2Router02(params.router);

        router.swapExactETHForTokensSupportingFeeOnTransferTokens{
            value: params.amountIn
        }(
            (params.minFirstAmountOut * (MAX_PERCENTAGE - params.slippage)) /
                MAX_PERCENTAGE,
            params.path,
            params.to[0],
            block.timestamp + 1 minutes
        );

        for (uint256 i = 1; i < params.to.length; i++) {
            router.swapExactETHForTokensSupportingFeeOnTransferTokens{
                value: params.amountIn
            }(0, params.path, params.to[i], block.timestamp + 1 minutes);
        }
    }

    function createVolETHV3(
        CreateVolV3Params calldata params
    ) external payable override(IVolumnSwap) whenNotPaused {
        require(msg.value == params.amountIn, "VolumnSwap::not enough amount");
        require(
            params.path.length == params.fee.length + 1,
            "VolumnSwap::not enough length"
        );
        require(
            params.path.length <= type(uint32).max,
            "VolumnSwap::overflow path length"
        );

        IWETH9(params.path[0]).deposit{ value: address(this).balance }();

        _createVolETHV3(params);
    }

    function withdraw(address _weth) external onlyOwner {
        IWETH9 weth = IWETH9(_weth);
        weth.withdraw(weth.balanceOf(address(this)));
        _withdraw(_msgSender(), address(this).balance);
    }

    function pause() external onlyOwner {
        _pause();
    }

    function unpause() external onlyOwner {
        _unpause();
    }

    function _createVolETHV2(CreateVolV2Params calldata params) private {
        IUniswapV2Router02 router = IUniswapV2Router02(params.router);
        IERC20 token = IERC20(params.path[params.path.length - 1]);
        IWETH9 weth = IWETH9(params.path[0]);
        weth.approve(params.router, type(uint256).max);
        token.approve(params.router, type(uint256).max);

        for (uint32 i = 0; i < params.loopTimes; i++) {
            router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
                weth.balanceOf(address(this)),
                0,
                params.path,
                address(this),
                block.timestamp + 1 minutes
            );

            if (i == 0) {
                uint256 minAmountOut = (params.minFirstAmountOut *
                    (MAX_PERCENTAGE - params.slippage)) / (MAX_PERCENTAGE);
                require(
                    token.balanceOf(address(this)) >= minAmountOut,
                    "VolumnSwap::mev bot comming..."
                );
            }

            router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
                token.balanceOf(address(this)),
                0,
                reversePath(params.path),
                address(this),
                block.timestamp + 1 minutes
            );
        }
    }

    function _createVolETHV2NoSlippage(
        CreateVolV2NoSlippageParams calldata params
    ) private {
        IUniswapV2Router02 router = IUniswapV2Router02(params.router);
        IERC20 token = IERC20(params.path[params.path.length - 1]);
        IWETH9 weth = IWETH9(params.path[0]);
        weth.approve(params.router, type(uint256).max);
        token.approve(params.router, type(uint256).max);

        for (uint32 i = 0; i < params.loopTimes; i++) {
            router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
                weth.balanceOf(address(this)),
                0,
                params.path,
                address(this),
                block.timestamp + 1 minutes
            );

            router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
                token.balanceOf(address(this)),
                0,
                reversePath(params.path),
                address(this),
                block.timestamp + 1 minutes
            );
        }
    }

    // 0xc35DADB65012eC5796536bD9864eD8773aBc74C4
    function _createVolETHV3(CreateVolV3Params calldata params) private {
        IV3SwapRouter router = IV3SwapRouter(params.swapRouter);
        IERC20 token = IERC20(params.path[params.path.length - 1]);
        IWETH9 weth = IWETH9(params.path[0]);
        weth.approve(params.swapRouter, type(uint256).max);
        token.approve(params.swapRouter, type(uint256).max);

        bytes memory _path = "";

        for (uint8 i = 0; i < params.fee.length; i++) {
            _path = bytes.concat(
                _path,
                bytes20(params.path[i]),
                bytes3(params.fee[i]),
                bytes20(params.path[i + 1])
            );
        }

        bytes memory _reversePath = "";

        for (uint8 i = uint8(params.fee.length); i >= 1; i--) {
            _reversePath = bytes.concat(
                _reversePath,
                bytes20(params.path[i]),
                bytes3(params.fee[i - 1]),
                bytes20(params.path[i - 1])
            );
        }

        for (uint32 i = 0; i < params.loopTimes; i++) {
            router.exactInput(
                IV3SwapRouter.ExactInputParams({
                    path: _path,
                    recipient: address(this),
                    amountIn: weth.balanceOf(address(this)),
                    amountOutMinimum: 0
                })
            );

            if (i == 0) {
                uint256 minAmountOut = (params.minFirstAmountOut *
                    (MAX_PERCENTAGE - params.slippage)) / (MAX_PERCENTAGE);
                require(
                    token.balanceOf(address(this)) >= minAmountOut,
                    "VolumnSwap::mev bot comming..."
                );
            }

            router.exactInput(
                IV3SwapRouter.ExactInputParams({
                    path: _reversePath,
                    recipient: address(this),
                    amountIn: token.balanceOf(address(this)),
                    amountOutMinimum: 0
                })
            );
        }
    }

    function _withdraw(address _to, uint256 _amount) internal {
        (bool success, ) = payable(_to).call{ value: _amount }("");
        require(success, "VolumnSwap::withdraw failed");
    }

    function reversePath(
        address[] calldata _array
    ) internal pure returns (address[] memory) {
        uint256 length = _array.length;
        address[] memory reversedArray = new address[](length);
        uint256 j = 0;
        for (uint256 i = length; i >= 1; i--) {
            reversedArray[j] = _array[i - 1];
            j++;
        }
        return reversedArray;
    }
}