// File: src/DividendsPairStaking.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import {IUniswapV2Factory} from "v2-core/interfaces/IUniswapV2Factory.sol";
import {IUniswapV2Router02} from "v2-periphery/interfaces/IUniswapV2Router02.sol";
import {IUniswapV2Pair} from "v2-core/interfaces/IUniswapV2Pair.sol";
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {IDividendsPairStaking} from "./interfaces/IDividendsPairStaking.sol";

/**
 * Twitter: https://twitter.com/mucushq
 * Website: https://mucus.io
 */
contract DividendsPairStaking is IDividendsPairStaking {
    uint256 public totalDogFactionAmount;
    uint256 public totalFrogFactionAmount;
    uint256 public dividendsPerFrog;
    uint256 public dividendsPerDog;
    mapping(address => Staker) public stakers;
    uint256 public totalStakedAmount;

    mapping(uint256 => SoupCycle) public soupCycles;
    uint256 public currentSoupIndex;
    uint256 public soupCycleDuration = 3 days;

    IUniswapV2Router02 public router;
    IERC20 public pair;
    address private _mucus;
    address private _owner;

    constructor(address mucus) {
        router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
        address _pair = IUniswapV2Factory(router.factory()).getPair(mucus, router.WETH());
        pair = IERC20(_pair);
        _mucus = mucus;
        _owner = msg.sender;

        soupCycles[currentSoupIndex] = SoupCycle({timestamp: block.timestamp, soupedUp: Faction.FROG, totalFrogWins: 1});
    }

    modifier onlyTokenOrOwner() {
        require(msg.sender == _mucus || msg.sender == _owner);
        _;
    }

    modifier onlyOwner() {
        require(msg.sender == _owner);
        _;
    }

    function addStake(Faction faction, uint256 tokenAmountOutMin) external payable {
        require(msg.value > 0, "ETH must be sent to stake");
        Staker memory staker = stakers[msg.sender];

        // This is equivalent to taring it to 0
        // This makes it so that the math to calculate the dps stays consistent
        if (staker.totalAmount > 0) {
            _distributeDividend(staker);
        }

        uint256 amount = _addLiquidity(tokenAmountOutMin);

        // add staker if never staked before
        if (staker.totalAmount == 0) {
            staker.previousDividendsPerFrog = dividendsPerFrog;
            staker.previousDividendsPerDog = dividendsPerDog;
        }

        staker.lockingEndDate = block.timestamp + 2 weeks;
        staker.totalAmount += amount;

        if (faction == Faction.DOG) {
            staker.dogFactionAmount += amount;
            totalDogFactionAmount += amount;
        } else {
            staker.frogFactionAmount += amount;
            totalFrogFactionAmount += amount;
        }
        totalStakedAmount += amount;

        stakers[msg.sender] = staker;

        emit StakeAdded(msg.sender, amount, faction);
    }

    function _addLiquidity(uint256 tokenAmountOutMin) private returns (uint256) {
        uint256 ethAmount = msg.value >> 1;
        uint256 tokenAmount = _swapEthForTokens(ethAmount, tokenAmountOutMin);

        // approve token transfer to cover all possible scenarios
        IERC20(_mucus).approve(address(router), tokenAmount);

        // add the liquidity
        (,, uint256 liquidity) = router.addLiquidityETH{value: ethAmount}(
            _mucus,
            tokenAmount,
            0, // slippage is unavoidable
            0, // slippage is unavoidable
            address(this),
            block.timestamp
        );

        return liquidity;
    }

    function _swapEthForTokens(uint256 ethAmount, uint256 tokenAmountOutMin) private returns (uint256) {
        // generate the uniswap pair path of token -> weth
        address[] memory path = new address[](2);
        path[0] = router.WETH();
        path[1] = address(_mucus);

        uint256[] memory amounts =
            router.swapExactETHForTokens{value: ethAmount}(tokenAmountOutMin, path, address(this), block.timestamp);

        return amounts[1];
    }

    function removeStake(uint256 amount, Faction faction) external {
        Staker memory staker = stakers[msg.sender];
        require(amount > 0, "Amount must be greater than 0");
        require(staker.totalAmount >= amount, "Cannot unstake more than you have staked");
        require(
            faction != Faction.DOG || staker.dogFactionAmount >= amount,
            "Cannot unstake more than you have staked for the dog faction"
        );
        require(
            faction != Faction.FROG || staker.frogFactionAmount >= amount,
            "Cannot unstake more than you have staked for the frog faction"
        );
        require(block.timestamp > staker.lockingEndDate, "Cannot unstake until locking period is over");

        // This is equivalent to taring it to 0
        // This makes it so that the math to calculate the dps stays consistent
        _distributeDividend(staker);

        if (faction == Faction.DOG) {
            staker.dogFactionAmount -= amount;
            totalDogFactionAmount -= amount;
        } else {
            staker.frogFactionAmount -= amount;
            totalFrogFactionAmount -= amount;
        }

        if (staker.totalAmount == amount) {
            delete stakers[msg.sender];
        } else {
            staker.totalAmount -= amount;
            stakers[msg.sender] = staker;
        }

        totalStakedAmount -= amount;

        pair.approve(address(router), amount);
        (uint256 tokenAmount, uint256 ethAmount) = router.removeLiquidityETH(
            _mucus,
            amount,
            0, // slippage is unavoidable
            0, // slippage is unavoidable
            address(this),
            block.timestamp
        );

        IERC20(_mucus).transfer(msg.sender, tokenAmount);
        payable(msg.sender).transfer(ethAmount);

        emit StakeRemoved(msg.sender, amount, faction);
    }

    function vote(uint256 amount, Faction faction) external {
        Staker memory staker = stakers[msg.sender];
        require(amount > 0, "Amount must be greater than 0");
        require(staker.totalAmount > 0, "Cannot vote if you haven't staked");

        // reset to make it consistent
        _distributeDividend(staker);

        if (faction == Faction.FROG) {
            require(staker.dogFactionAmount >= amount, "Cannot swap more Dog votes than you have staked");

            staker.dogFactionAmount -= amount;
            staker.frogFactionAmount += amount;
            totalDogFactionAmount -= amount;
            totalFrogFactionAmount += amount;
        } else {
            require(staker.frogFactionAmount >= amount, "Cannot swap more Frog votes than you have staked");

            staker.frogFactionAmount -= amount;
            staker.dogFactionAmount += amount;
            totalFrogFactionAmount -= amount;
            totalDogFactionAmount += amount;
        }

        stakers[msg.sender] = staker;

        emit VoteSwapped(msg.sender, amount, faction);
    }

    function claim() external {
        Staker memory staker = stakers[msg.sender];
        require(staker.totalAmount > 0, "Cannot claim if you haven't staked");
        _distributeDividend(staker);
    }

    function _distributeDividend(Staker memory staker) internal {
        uint256 frogRewards = (dividendsPerFrog - staker.previousDividendsPerFrog) * staker.frogFactionAmount;
        uint256 dogRewards = (dividendsPerDog - staker.previousDividendsPerDog) * staker.dogFactionAmount;

        staker.previousDividendsPerFrog = dividendsPerFrog;
        staker.previousDividendsPerDog = dividendsPerDog;

        stakers[msg.sender] = staker;

        if (frogRewards + dogRewards > 0) {
            IERC20(_mucus).transfer(msg.sender, frogRewards + dogRewards);
        }

        emit DividendsEarned(msg.sender, frogRewards + dogRewards);
    }

    function deposit(uint256 amount) external onlyTokenOrOwner {
        if (amount > 0 && totalFrogFactionAmount > 0 && totalDogFactionAmount > 0) {
            uint256 frogAmount = amount * totalDogFactionAmount / totalStakedAmount;
            uint256 dogAmount = amount - frogAmount;
            dividendsPerFrog += frogAmount / totalFrogFactionAmount;
            dividendsPerDog += dogAmount / totalDogFactionAmount;
        }

        emit DividendsPerShareUpdated(dividendsPerFrog, dividendsPerDog);
    }

    function cycleSoup() external onlyTokenOrOwner {
        require(
            block.timestamp >= soupCycles[currentSoupIndex].timestamp + soupCycleDuration,
            "Cannot update soup cycle until the current cycle is over"
        );
        uint256 totalFrogWins = soupCycles[currentSoupIndex].totalFrogWins;
        Faction soupedUp = totalFrogFactionAmount > totalDogFactionAmount ? Faction.FROG : Faction.DOG;
        if (soupedUp == Faction.FROG) totalFrogWins++;

        currentSoupIndex++;
        soupCycles[currentSoupIndex] =
            SoupCycle({timestamp: block.timestamp, soupedUp: soupedUp, totalFrogWins: totalFrogWins});

        emit SoupCycled(currentSoupIndex, soupedUp);
    }

    function getSoup(uint256 previousSoupIndex)
        external
        view
        returns (uint256, uint256, SoupCycle memory, SoupCycle memory)
    {
        return (currentSoupIndex, soupCycleDuration, soupCycles[previousSoupIndex], soupCycles[currentSoupIndex]);
    }

    function nextSoupCycle() external view returns (uint256) {
        return soupCycles[currentSoupIndex].timestamp + soupCycleDuration;
    }

    function getSoupedUp() external view returns (Faction) {
        return soupCycles[currentSoupIndex].soupedUp;
    }

    function setSoupCycleDuration(uint256 _soupCycleDuration) external onlyOwner {
        soupCycleDuration = _soupCycleDuration;

        emit SoupCycleDurationUpdated(_soupCycleDuration);
    }

    function withdrawMucus() external onlyOwner {
        IERC20 mucus = IERC20(_mucus);
        mucus.transfer(msg.sender, mucus.balanceOf(address(this)));
    }

    function withdrawEth() external onlyOwner {
        (bool success,) = payable(msg.sender).call{value: address(this).balance}("");
        require(success, "Failed to send ETH");
    }

    receive() external payable {}
}

// File: lib/v2-core/contracts/interfaces/IUniswapV2Factory.sol



pragma solidity >=0.5.0;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

// File: lib/v2-periphery/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: lib/v2-core/contracts/interfaces/IUniswapV2Pair.sol



pragma solidity >=0.5.0;

interface IUniswapV2Pair {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() external view returns (uint);
    function kLast() external view returns (uint);

    function mint(address to) external returns (uint liquidity);
    function burn(address to) external returns (uint amount0, uint amount1);
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
}

// File: lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.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: src/interfaces/IDividendsPairStaking.sol



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

interface IDividendsPairStaking {
    enum Faction {
        DOG,
        FROG
    }

    struct Staker {
        uint256 totalAmount;
        uint256 frogFactionAmount;
        uint256 dogFactionAmount;
        uint256 previousDividendsPerFrog;
        uint256 previousDividendsPerDog;
        uint256 lockingEndDate;
    }

    struct SoupCycle {
        uint256 timestamp;
        Faction soupedUp;
        uint256 totalFrogWins;
    }

    event StakeAdded(address indexed staker, uint256 amount, Faction faction);
    event StakeRemoved(address indexed staker, uint256 amount, Faction faction);
    event VoteSwapped(address indexed staker, uint256 amount, Faction faction);
    event DividendsPerShareUpdated(uint256 dividendsPerFrog, uint256 dividendsPerDog);
    event DividendsEarned(address indexed staker, uint256 amount);
    event SoupCycled(uint256 indexed soupIndex, Faction soupedUp);
    event SoupCycleDurationUpdated(uint256 soupCycleDuration);

    function stakers(address staker) external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
    function currentSoupIndex() external view returns (uint256);
    function addStake(Faction faction, uint256 tokenAmountOutMin) external payable;
    function removeStake(uint256 amount, Faction faction) external;
    function vote(uint256 amount, Faction faction) external;
    function claim() external;
    function deposit(uint256 amount) external;
    function cycleSoup() external;
    function getSoup(uint256 previousSoupIndex)
        external
        view
        returns (uint256, uint256, SoupCycle memory, SoupCycle memory);
    function nextSoupCycle() external view returns (uint256);
    function getSoupedUp() external view returns (Faction);
    function setSoupCycleDuration(uint256 _soupCycleDuration) external;
    function withdrawMucus() external;
    function withdrawEth() external;
}

// File: lib/v2-periphery/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);
}