// 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/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/factory/QWAFactory.sol



pragma solidity 0.8.19;

import "../interface/factory/IQWATokenFactory.sol";
import "../interface/factory/ITreasuryAndStakedTokenFactory.sol";
import "../interface/factory/IStakingAndDistributorFactory.sol";
import "../interface/IUniswapV2Router02.sol";
import "../interface/IQWA.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract QWAFactory is Ownable {
    /// EVENTS ///

    event Created(
        uint256 creationId,
        address indexed deployer,
        address _QWA,
        address _treasury,
        address _sQWA,
        address _staking,
        address _distributor
    );

    /// STATES VARIABLES ///
    IQWATokenFactory public qwaTokenFactory;
    ITreasuryAndStakedTokenFactory public treasuryAndStakedTokenFatory;
    IStakingAndDistributorFactory public stakingAndDistributorFactory;
    IUniswapV2Router02 public uniswapV2Router;

    uint256 public creationId;
    uint256 public maxTokenPercent;
    uint256 public percentNeededForDiscount;

    address public immutable WETH;
    address public immutable QWN;
    address public immutable sQWN;
    address public immutable QWNStaking;
    address public feeAddress;

    address[] public discountTokens;
    uint256[] public discountTokensNeeded;

    mapping(address => bool) public removedFromDiscount;

    mapping(uint256 => CreationDetails) public creationDetails;

    /// STRUCTS ///

    struct CreationDetails {
        address QWA;
        address treasury;
        address sQWA;
        address staking;
        address distributor;
    }

    /// CONSTRUCTOR ///

    constructor(
        address _weth,
        address _qwn,
        address _sQWN,
        address _qwnStaking,
        address _feeAddress
    ) {
        WETH = _weth;
        QWN = _qwn;
        sQWN = _sQWN;
        QWNStaking = _qwnStaking;
        feeAddress = _feeAddress;

        IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
            0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
        );

        uniswapV2Router = _uniswapV2Router;

        percentNeededForDiscount = 15;
        maxTokenPercent = 5;
    }

    /// CREATE FUNCTION ///

    /// @notice                       Create QWA token and contracts
    /// @param _backingTokens         Tokens to be used for backing
    /// @param _backingTokensV3Fee    What pool fee for v3 (0 if v2)
    /// @param _backingAmounts        Backing amount of token
    /// @param _nameAndSymbol         Name and symbol of token
    /// @param _creatorSupplyPercent  Creator percent of supply
    /// @param _owner                 Pass ownership to
    function create(
        address[] memory _backingTokens,
        uint24[] memory _backingTokensV3Fee,
        uint256[] memory _backingAmounts,
        string[2] memory _nameAndSymbol,
        uint256 _creatorSupplyPercent,
        address _owner
    )
        external
        payable
        returns (
            address _QWAAddress,
            address _treasuryAddress,
            address _sQWAAddress,
            address _stakingAddress,
            address _distributorAddress
        )
    {
        require(
            _creatorSupplyPercent <= maxTokenPercent,
            "Can not send team more than max percent"
        );
        require(
            _backingTokens.length == _backingAmounts.length &&
                _backingTokensV3Fee.length == _backingAmounts.length,
            "Different array lengths"
        );

        require(_backingTokens.length > 0, "Can not have no backing tokens");

        require(
            msg.value >= 0.5 ether,
            "Can not add less than 0.5 ETH liquidity"
        );

        for (uint i; i < _backingTokens.length; i++) {
            require(
                _backingAmounts[i] > 0,
                "Backing amount needs to be greater than 0"
            );
            require(
                _backingTokensV3Fee[i] == 0 ||
                    _backingTokensV3Fee[i] == 500 ||
                    _backingTokensV3Fee[i] == 3000 ||
                    _backingTokensV3Fee[i] == 10000,
                "Invalid V3 pool fee (0.05%, 0.3%, 1%)"
            );
        }

        _QWAAddress = qwaTokenFactory.create(
            WETH,
            _backingTokens,
            _backingTokensV3Fee,
            _nameAndSymbol
        );

        bool _qwnBackingToken;
        for (uint i; i < _backingTokens.length; ++i) {
            if (_backingTokens[i] == QWN) {
                _qwnBackingToken = true;
                break;
            }
        }

        (_treasuryAddress, _sQWAAddress) = treasuryAndStakedTokenFatory.create(
            _QWAAddress,
            _backingTokens,
            _backingAmounts,
            _nameAndSymbol,
            _qwnBackingToken
        );

        (_stakingAddress, _distributorAddress) = stakingAndDistributorFactory
            .create(_QWAAddress, _sQWAAddress, _treasuryAddress, _owner);

        qwaTokenFactory.setTreasury(_treasuryAddress, _QWAAddress, _owner);
        treasuryAndStakedTokenFatory.setDistributorAndInitialize(
            _distributorAddress,
            _stakingAddress,
            _treasuryAddress,
            _sQWAAddress,
            _owner
        );

        if (_creatorSupplyPercent > 0) {
            uint256 _teamMint = (IERC20(_QWAAddress).balanceOf(address(this)) *
                _creatorSupplyPercent) / 100;
            IERC20(_QWAAddress).transfer(_owner, _teamMint);
        }

        uint256 _balance = IERC20(_QWAAddress).balanceOf(address(this));
        IERC20(_QWAAddress).approve(address(uniswapV2Router), _balance);
        uniswapV2Router.addLiquidityETH{value: msg.value}(
            _QWAAddress,
            _balance,
            0,
            0,
            _treasuryAddress,
            block.timestamp
        );

        CreationDetails storage _creationDetails = creationDetails[creationId];
        _creationDetails.QWA = _QWAAddress;
        _creationDetails.treasury = _treasuryAddress;
        _creationDetails.sQWA = _sQWAAddress;
        _creationDetails.staking = _stakingAddress;
        _creationDetails.distributor = _distributorAddress;

        emit Created(
            creationId,
            msg.sender,
            _QWAAddress,
            _treasuryAddress,
            _sQWAAddress,
            _stakingAddress,
            _distributorAddress
        );

        creationId++;
    }

    /// OWNER FUNCTION ///

    /// @notice Set factory address
    function setFactoryAddresses(
        address _qwaTokenFactory,
        address _treasuryAndStakedTokenFatory,
        address _stakingAndDistributorFactory
    ) external onlyOwner {
        require(
            address(qwaTokenFactory) == address(0),
            "Addresses already set"
        );
        qwaTokenFactory = IQWATokenFactory(_qwaTokenFactory);
        treasuryAndStakedTokenFatory = ITreasuryAndStakedTokenFactory(
            _treasuryAndStakedTokenFatory
        );
        stakingAndDistributorFactory = IStakingAndDistributorFactory(
            _stakingAndDistributorFactory
        );
    }

    /// @notice Set fee address to query
    function setFeeAddress(address _feeAddress) external onlyOwner {
        feeAddress = _feeAddress;
    }

    /// @notice Set max token percent creator can take
    function setMaxTokenPercent(uint256 _maxPercent) external onlyOwner {
        maxTokenPercent = _maxPercent;
    }

    /// @notice Set percent of QWN supply in sQWN to receive discount on fees
    function setPercentNeededForDiscount(uint256 _percent) external onlyOwner {
        percentNeededForDiscount = _percent;
    }

    /// @notice Remove address from having discount on fees
    function setRemovedFromDiscount(
        address _user,
        bool _removed
    ) external onlyOwner {
        removedFromDiscount[_user] = _removed;
    }

    /// @notice Set tokens and amounts to receive discount on QWA fees
    function setDiscountTokens(
        address[] calldata _tokens,
        uint256[] calldata _amounts
    ) external onlyOwner {
        require(_tokens.length == _amounts.length, "Different array lengths");

        discountTokens = _tokens;
        discountTokensNeeded = _amounts;
    }

    // VIEW FUNCTION ///

    /// @notice           Returns if address has discount on QWA fees
    /// @param _user      Address to check receives discount on fees
    /// @param _discount  Bool if has discount on fees
    function feeDiscount(address _user) external view returns (bool _discount) {
        if (removedFromDiscount[_user]) return false;
        uint256 sQWNBalance = IERC20(sQWN).balanceOf(_user);
        uint256 QWNSupply = IERC20(QWN).totalSupply();
        if (sQWNBalance >= (QWNSupply * percentNeededForDiscount) / 10000)
            return true;

        for (uint i; i < discountTokens.length; ++i) {
            if (
                IERC20(discountTokens[i]).balanceOf(_user) >=
                discountTokensNeeded[i]
            ) return true;
        }
    }

    /// @notice             Returns addrseses of creation
    /// @param _creationId  Creation id to return address for
    function created(
        uint256 _creationId
    ) external view returns (CreationDetails memory) {
        return creationDetails[_creationId];
    }
}

// File: contracts/interface/factory/IQWATokenFactory.sol



// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.19;

interface IQWATokenFactory {
    function create(
        address _weth,
        address[] calldata _backingTokens,
        uint24[] calldata _backingTokensV3Fee,
        string[2] calldata _nameAndSymbol
    ) external returns (address _QWAAddress);

    function setTreasury(address _treasury, address _QWA, address _owner) external;
}

// File: contracts/interface/factory/IStakingAndDistributorFactory.sol



// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.19;

interface IStakingAndDistributorFactory {
    function create(
        address _qwa,
        address _sQWA,
        address _treasury,
        address _owner
    ) external returns (address _stakingAddress, address _distributorAddress);
}

// File: contracts/interface/factory/ITreasuryAndStakedTokenFactory.sol



// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.19;

interface ITreasuryAndStakedTokenFactory {
    function create(
        address _qwa,
        address[] calldata _backingTokens,
        uint256[] calldata _backingAmounts,
        string[2] calldata _nameAndSymbol,
        bool _qwnBackingToken
    ) external returns (address _treasuryAddress, address _sQWAAddress);

    function setDistributorAndInitialize(
        address _distributor,
        address _staking,
        address _treasury,
        address _sQWA,
        address _owner
    ) external;
}

// File: contracts/interface/IQWA.sol



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

pragma solidity 0.8.19;

interface IQWA is IERC20Metadata {
    function mint(address to_, uint256 amount_) external;

    function burnFrom(address account_, uint256 amount_) external;

    function burn(uint256 amount_) external;

    function uniswapV2Pair() external view returns (address);

    function treasury() external view returns (address);
}

// File: contracts/interface/IUniswapV2Router02.sol



pragma solidity 0.8.19;

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

    function WETH() external pure returns (address);

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

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

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

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

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

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