contract Tetraguard is ITetraguard, ERC20 {

    // Declare uniswap V2 router.  External but trusted contract maintained by Uniswap.org
    IUniswapV2Router02 private uniswapRouter;

    // Declare Quadron Token interface
    IQuadron private qToken;

    // -- Declare addresses for uniswap router, uniswap pairs, and reserve contract --
    address private UNISWAP_ROUTER_ADDRESS; // 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
    address private PAXG; // 0x45804880De22913dAFE09f4980848ECE6EcbAf78;
    address private WBTC; // 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
    address private RESERVE;
    address private UPGRADE_TOKEN;

    // -- Ratios of coins --
    uint32 private constant R_WBTC = 1;
    uint32 private constant R_ETH = 13;
    uint32 private constant R_PAXG = 26;
    uint32 private constant R_RESERVE = 23632;

    // -- Constants--
    // supply of quadrons at the end of phase 1
    uint256 internal constant PHASE_1_END_SUPPLY = 65e6 * 1e18; 
    // supply of quadrons at the end of phase 1
    uint256 internal constant PHASE_2_END_SUPPLY = 68333333333333333333333333;
    // maximum buy order size (ether)
    uint256 internal constant MAX_BUY_ORDER = 2000 ether;
    // maximum sell order size (Tetraguard)
    uint256 internal constant MAX_SELL_ORDER = 400e3 * 1e18;    

    // -- Track remaining bonus tokens, used in the event of rounding errors --
    uint256 private remAlphaBonus = 7.5e6 * 1e18;
    uint256 private remBetaBonus = 4.5e6 * 1e18;
    uint256 private remGammaBonus = 3e6 * 1e18;
    uint256 private remAlphaRTokens = 6666666666666666666666667;
    uint256 private remBetaRTokens = 6666666666666666666666667;
    uint256 private remGammaRTokens = 6666666666666666666666666;
        
    // -- Declare state variables --
    address private owner;  // Contract owner

    /** @dev Tetraguard Token Constructor
     *  @param _quadron Address of Quadron
     *  @param _paxg Address of PAXG
     *  @param _wbtc Address of WBTC
     *  @param _uniswapRouter Address of Uniswap V2 Router     
     */
    constructor(address _quadron, address _paxg, address _wbtc, address _uniswapRouter) 
        ERC20("Tetraguard", "TETRA") {
        
        // Instantiate uniswap router
        uniswapRouter = IUniswapV2Router02(_uniswapRouter);

        // Instantiate quadron
        qToken = IQuadron(_quadron);

        // Assign contract owner
        owner = address(msg.sender);

        UNISWAP_ROUTER_ADDRESS = _uniswapRouter;
        PAXG = _paxg;
        WBTC = _wbtc;
        RESERVE = _quadron;
        UPGRADE_TOKEN = msg.sender; // Initially, set the upgrade token address to the owner
    }

    /** @dev Exchanges sent Ether for Tetraguard tokens, which represents a basket of tokens
     * @param deadline Deadline after which the transaction will revert if not processed
     * @param priceWBTC Max price (in wei) for one unit of wbtc
     * @param pricePAXG Max price (in wei) for one unit of paxg
     */
    function buy(uint256 deadline, uint256 priceWBTC, uint256 pricePAXG) external payable {
        require(deadline >= block.timestamp, "Deadline expired");
        require(msg.value <= MAX_BUY_ORDER, "Buy exceeded the maximum purchase amount");
        
        uint256 PriceOfBase;
        uint256 PriceOfBaseWBTC;
        uint256 PriceOfBasePAXG;
        uint256 PriceOfBaseEth;
        uint256 PriceOfReserve;
        uint256 prevRTokenTotalSupply = qToken.totalSupply();
        uint256 balance = address(this).balance;

        // This is the lowest price (in WEI) of one unit of Tetraguard (1e-4 Tetraguard)
        (PriceOfBase, PriceOfBaseWBTC, PriceOfBasePAXG, PriceOfBaseEth, PriceOfReserve) = getPriceOfBase();
        
        // Now calculate how many units of Tetraguard we can purchase
        require(baseTokensToMint(PriceOfBase) >= 1, "Not enough Ether to purchase .0001 Tetraguard");
       
        require(1e4 * PriceOfBaseWBTC / R_WBTC <= priceWBTC, "Maximum wbtc price exceeded.");
        require(1e4 * PriceOfBasePAXG / R_PAXG <= pricePAXG, "Maximum paxg price exceeded.");

        // Transfer 1% of the Base Price to quadron
        payable(RESERVE).transfer(PriceOfBase * baseTokensToMint(PriceOfBase) * 1 / 100);

        // 101/100 send 1% more in case of underflow
        qToken.buy{value: baseTokensToMint(PriceOfBase) * PriceOfReserve * 101 / 100}(reserveTokensToMint(baseTokensToMint(PriceOfBase)));

        // Purchase WBTC
        //   1e4 accounts for 8 decimal places of WBTC, and that minimum purchase by this contract is 1e-4
        uniswapRouter.swapETHForExactTokens{ 
            value: (baseTokensToMint(PriceOfBase) * PriceOfBaseWBTC * 101 / 100) 
            }(baseTokensToMint(PriceOfBase) * R_WBTC * 1e4, getPathForETHtoToken(WBTC), address(this), deadline);

        // Purchase PAXG
        //   (10000 / 9998) to account for the PAXG 0.02% fee
        uniswapRouter.swapETHForExactTokens{ 
            value: (baseTokensToMint(PriceOfBase) * PriceOfBasePAXG * 101 / 100) 
            }(baseTokensToMint(PriceOfBase) * R_PAXG * 1e14 * 10000 / 9998, getPathForETHtoToken(PAXG), address(this), deadline);

        balance = msg.value - (balance - address(this).balance);  // amount of eth left in this transaction

        // Early Buyer Bonus
        if(prevRTokenTotalSupply <= PHASE_1_END_SUPPLY) {
            bool success = qToken.transfer(msg.sender, calcBonusTokens(reserveTokensToMint(baseTokensToMint(PriceOfBase))));
            require(success, "Early buyer bonus transfer failed.");
        }
        
        // Mint the Tetraguard Token (basket of coins)
        _mint(msg.sender, baseTokensToMint(PriceOfBase) * 1e14);

        // Refund any leftover ETH that the contract has to the user, minus amount kept for basket.  
        //   This takes care of the ether portion of the basket, as well
        (bool successRefund,) = msg.sender.call{ value: (balance - amountEthInCoin(baseTokensToMint(PriceOfBase), PriceOfBaseEth)) }("");
        require(successRefund, "Refund failed");        
    }

    /** @dev Exchanges your Tetraguard Tokens for Ether, by unwrapping the basket 
     * of tokens and selling at market price
     * @param amount Amount of Tetraguard Token to exchange for Ether
     * @param deadline Deadline after which the transaction will revert if not processed
     * @param priceWBTC Min price (in wei) for one unit of wbtc
     * @param pricePAXG Min price (in wei) for one unit of paxg     
     */
    function sell(uint256 amount, uint256 deadline, uint256 priceWBTC, uint256 pricePAXG) external payable {
        require(balanceOf(msg.sender) >= amount, "Insufficient Tetraguard to sell");
        require(deadline >= block.timestamp, "Deadline expired");
        require(amount <= MAX_SELL_ORDER, "Sell exceeded maximum sale amount");

        bool success;

        uint256 amountBaseToken = (amount / 1e14) * 1e14;  // Get floor.  Mimimum amount of Tetraguard Tokens to transact is .0001
        require(amountBaseToken >= 1e14, "The minimum sale amount is .0001 token");

        uint256 MinProceedsWBTC;
        uint256 MinProceedsPAXG;
        
        (MinProceedsWBTC, MinProceedsPAXG) = estimateProceeds(amountBaseToken);

        require(1e18 * MinProceedsWBTC / (amountBaseToken * R_WBTC) >= priceWBTC, "Minimum wbtc price not met.");
        require(1e18 * MinProceedsPAXG / (amountBaseToken * R_PAXG) >= pricePAXG, "Minimum paxg price not met.");

        uint256 coinValueStart = address(this).balance;

        // Swap PAXG and WBTC back to ETH
        require(IERC20(WBTC).approve(address(UNISWAP_ROUTER_ADDRESS), 
            amountBaseToken * R_WBTC / 1e10), 'Approve failed');
        uniswapRouter.swapExactTokensForETH(amountBaseToken * R_WBTC / 1e10, MinProceedsWBTC, getPathFoqTokentoETH(WBTC), address(this), deadline);  // 1e10 accounts for 8 decimal places of WBTC, and that minimum purchase by this contract is 1e-4
        
        require(IERC20(PAXG).approve(address(UNISWAP_ROUTER_ADDRESS), amountBaseToken * R_PAXG), 'Approve failed');
        uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(amountBaseToken * R_PAXG, MinProceedsPAXG, getPathFoqTokentoETH(PAXG), address(this), deadline);

        // If in Phase 3, sell Quadrons
        if(qToken.getPhase() == 3) {
            qToken.sell(amountBaseToken * R_RESERVE);
        } else {
            // return Quadrons tokens to seller's wallet
            success = qToken.transfer(msg.sender, amountBaseToken * R_RESERVE);
            require(success, "Early buyer bonus transfer failed.");
        }

        uint coinValueEnd = address(this).balance;
        uint proceedsFromSwap = coinValueEnd - coinValueStart + (amountBaseToken * R_ETH);

        // Transfer 1% transaction fee
        payable(RESERVE).transfer(proceedsFromSwap * 1 / 100); // transfer 1% fee to the Quadron

        _burn(msg.sender, amountBaseToken);

        // Transfer sale of Tetraguard Tokens
        (success,) = msg.sender.call{ value: (proceedsFromSwap * 99 / 100)}("");
        require(success, "Payment failed");
    }

    /** @dev reserveTokensToMint calculates the number of Quadrons to mint
     *  @param tetraguardTokensToMint is the amount of base tokens
     */
    function reserveTokensToMint(uint256 tetraguardTokensToMint) internal pure returns (uint256) {
        return tetraguardTokensToMint * R_RESERVE * 1e14;
    }

    /** @dev baseTokensToMint calculates the number of quadrons to mint
     *  @param priceOfBase is the price of the base token in the basket
     */
    function baseTokensToMint(uint256 priceOfBase) internal view returns (uint256) {
        require(priceOfBase > 0, "The price of base token must be greater than zero");
        return msg.value / (101 * priceOfBase / 100);  // 1.01 represents the 1% Tetraguard fee
    }    

    /** @dev getPriceOfBase calculates the price (in wei) of the smallest tradable unit of Tetraguard.  The smallest
     *  tradable unit is .0001 Token (1e14).
     */
    function getPriceOfBase() internal view returns (uint256, uint256, uint256, uint256, uint256) {
        // We need to find the average cost of each token, assuming we would trade the entire msg.value.
        // This is done to ensure there is sufficient liquidity for the swap.
       
        // Assumes 0.0001 token will cost at least 0.0001 Eth (1e14 wei)
        require(msg.value >= 1e14, "Insufficient ether sent to purchase 0.0001 token");
        
        // Get the amount of tokens received in exchange for msg.value
        uint256 PAXGtoETH = uniswapRouter.getAmountsOut(msg.value, getPathForETHtoToken(PAXG))[1];
        uint256 WBTCtoETH = uniswapRouter.getAmountsOut(msg.value, getPathForETHtoToken(WBTC))[1];

        uint256 PriceOfBasePAXG;
        uint256 PriceOfBaseWBTC;
        uint256 PriceOfBaseEth = 1e14; // base price of Eth

        //*** Handle 3 scenarios in the event of future price changes:
        // 1) getAmountsOut < msg.value
        //    This happens when price of the token is less than 1 Eth.
        // 2) getAmountsOut returns 0
        //    This happens when price of token is much greater than msg.value
        // 3) getAmountsOut returns 1
        //    This happens when the price of the token is very similar to msg.value

        // Process PAXG
        // Calculate the average price (wei) for 0.0001 tokens
        require(PAXGtoETH > 0, "The price of PAXG is too high for this amount of Eth.");
        PriceOfBasePAXG = 1e14 * msg.value / PAXGtoETH;
        require(PriceOfBasePAXG > 0, "The price of PAXG has dropped too low to trade.");
        
        // Process WBTC
        // Calculate the average price (wei) for 0.0001 tokens
        require(WBTCtoETH > 0, "The price of WBTC is too high for this amount of Eth.");
        PriceOfBaseWBTC = 1e4 * msg.value / WBTCtoETH; // 1e4 is required to scale WBTC, since it uses a fewer decimals than Eth.
        require(PriceOfBaseWBTC > 0, "The price of WBTC has dropped to low to trade.");
        
        // Process Quadron
        uint256 PriceOfReserveEth = qToken.quoteAvgPriceForTokens(msg.value);

        // Apply ratios of coins
        PriceOfBasePAXG = R_PAXG * PriceOfBasePAXG * 10000 / 9998; // (10000 / 9998) to account for the PAXG 0.02% fee;
        PriceOfBaseEth = R_ETH * PriceOfBaseEth;
        PriceOfBaseWBTC = R_WBTC * PriceOfBaseWBTC;
        PriceOfReserveEth = R_RESERVE * PriceOfReserveEth / 1e4; // Scale to 0.0001 quadrons

        // This is the lowest price (in WEI) of one unit of Tetraguard
        return (PriceOfBaseWBTC + PriceOfBasePAXG + PriceOfBaseEth + PriceOfReserveEth, PriceOfBaseWBTC, PriceOfBasePAXG, PriceOfBaseEth, PriceOfReserveEth);
    }

    /** @dev estimateProceeds calculates the price (in wei) of the sale proceeds
     *  @param amount Amount of Tetraguard Token to exchange for Ether
     */
    function estimateProceeds(uint256 amount) internal view returns (uint256, uint256) {
        // Get the amount of eth received
        uint256 PAXGtoETH = uniswapRouter.getAmountsOut(amount * R_PAXG, getPathFoqTokentoETH(PAXG))[1];
        uint256 WBTCtoETH = uniswapRouter.getAmountsOut(amount * R_WBTC / 1e10, getPathFoqTokentoETH(WBTC))[1];

        uint256 PriceOfBasePAXG;
        uint256 PriceOfBaseWBTC;

        // (10000 / 9998) to account for the PAXG 0.02% fee
        PriceOfBasePAXG = PAXGtoETH * 9998 / 10000;
        PriceOfBaseWBTC = WBTCtoETH;

        // This is the lowest price (in WEI) for the amount of Tetraguard
        return (PriceOfBaseWBTC, PriceOfBasePAXG);
    }

    function getPathForETHtoToken(address tokenAddress) private view returns (address[] memory) {
        address[] memory path = new address[](2);
        path[0] = uniswapRouter.WETH();
        path[1] = tokenAddress;
        
        return path;
    }
    
    function getPathFoqTokentoETH(address tokenAddress) private view returns (address[] memory) {
        address[] memory path = new address[](2);
        path[0] = tokenAddress;
        path[1] = uniswapRouter.WETH();        
        
        return path;
    }

    /** @dev amountEthInCoin multiplies the tokens to mint by the base price of Eth
     *  @param tokensToMint number of Tetraguard tokens to mint
     *  @param priceOfBaseEth the price of eth
     *  @return tokensToMint * priceOfBaseEth
     */
    function amountEthInCoin(uint tokensToMint, uint priceOfBaseEth) private pure returns (uint) {
        // Calculate the amount of Ether in the coin
        return tokensToMint * priceOfBaseEth;
    }

    /** @dev calcBonusTokens calculates the number of bonus tokens to send the buyer
     *  @param qTokensToMint amount of new quadrons that are minted during the
     *  purchase of Tetraguard.
     *  @return total bonus tokens to transfer to the early buyer
     */    
    function calcBonusTokens(uint256 qTokensToMint) private returns (uint256) {
        uint256 alpha = 0;  // Amount of bonus tokens for phase alpha
        uint256 beta = 0;  // Amount of bonus tokens for phase beta
        uint256 gamma = 0;  // Amount of bonus tokens for phase gamma
        uint256 remainder = qTokensToMint;

        // Rounding errors create scenarios where some bonus quadrons
        // can get lost.  Iterate through each phase and zero out
        // remaining bonus tokens due to underflow.

        if(remainder > 0 && remAlphaRTokens > 0) {
            if(remainder > remAlphaRTokens) {
                remainder = remainder - remAlphaRTokens;
                remAlphaRTokens = 0;
                alpha = remAlphaBonus;
                remAlphaBonus = 0;
            } else {
                remAlphaRTokens = remAlphaRTokens - remainder;
                alpha = remainder * 1125 / 1000;
                remainder = 0;
                
                if(alpha > remAlphaBonus) {
                    alpha = remAlphaBonus;
                    remAlphaBonus = 0;
                    remAlphaRTokens = 0;
                } else {
                    remAlphaBonus = remAlphaBonus - alpha;
                }
            }
        }
        
        if(remainder > 0 && remBetaRTokens > 0) {
            if(remainder > remBetaRTokens) {
                remainder = remainder - remBetaRTokens;
                remBetaRTokens = 0;
                beta = remBetaBonus;
                remBetaBonus = 0;
            } else {
                remBetaRTokens = remBetaRTokens - remainder;
                beta = remainder * 675 / 1000;
                remainder = 0;
                
                if(beta > remBetaBonus) {
                    beta = remBetaBonus;
                    remBetaBonus = 0;
                    remBetaRTokens = 0;
                } else {
                    remBetaBonus = remBetaBonus - beta;
                }
            }            
        }
        
        if(remainder > 0 && remGammaRTokens > 0) {
            if(remainder > remGammaRTokens) {
                remGammaRTokens = 0;
                gamma = remGammaBonus;
                remGammaBonus = 0;
            } else {
                remGammaRTokens = remGammaRTokens - remainder;
                gamma = remainder * 45 / 100;
                
                if(gamma > remGammaBonus) {
                    gamma = remGammaBonus;
                    remGammaBonus = 0;
                    remGammaRTokens = 0;
                } else {
                    remGammaBonus = remGammaBonus - gamma;
                }
            }
        }
     
        return alpha + beta + gamma;
    }

    /** @dev Mints bonus Quadrons
      */  
    function mintBonusTokens() external isOwner {
        qToken.mintBonus();
    }

    /** @dev Sets the address of the upgrade token
     *  @param tokenAddress Address of the new token
     */
    function setUpgradeToken(address tokenAddress) external isOwner {
        UPGRADE_TOKEN = tokenAddress;
        qToken.addApprovedToken(tokenAddress);
    }

    /** @dev Exchanges Tetraguard tokens for the upgraded token.  This is an opt-in process.
     *  @param amount Amount of Tetraguard tokens to upgrade
     *  @return Unwrapped ether (wei)
     */
    function upgradeToken(uint256 amount, address tokenHolder) external override returns (uint256) {
        require(UPGRADE_TOKEN != address(0));
        require(msg.sender == UPGRADE_TOKEN, "Not authorized to upgrade");
        require(balanceOf(tokenHolder) >= amount, "Insufficient Tetraguard to upgrade");
        require(amount > 0, "Amount must be greater than zero");
        _burn(tokenHolder, amount); // burn the old token

        // Transfer PAXG, WBTC, Quadron
        require(IERC20(WBTC).transfer(address(msg.sender), amount * R_WBTC / 1e10), "WBTC transfer failed");
        require(IERC20(PAXG).transfer(msg.sender, amount * R_PAXG), "WBTC transfer failed");
        require(qToken.transfer(msg.sender, amount * R_RESERVE), "Quadron transfer failed");

        // Transfer Ether
        (bool success,) = msg.sender.call{ value: (amount * R_ETH)}("");
        require(success, "Transfer Tetraguard ether failed.");

        return (amount * R_ETH);
    }
  
    receive() external payable {
    }
    
    fallback() external payable {
    }
    
    // @dev Modifier to allow a function callable only by the owner.
    modifier isOwner() {
        require(msg.sender == owner);
        _;
    }
}
/** @title Tetraguard Contract. */
function mintBonusTokens() external isOwner {
        qToken.mintBonus();
    }
/** @dev Mints bonus Quadrons
 */