// 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/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/donorship.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./IV3Router.sol";
import "./IWETH.sol";
import "./IUSDT.sol";
import "./poolchecker.sol";
import "./IRouter02.sol";

contract DonorshipPaymentProcessor is Ownable, Pausable, ReentrancyGuard {
    //receiver of primary fee
    address public primaryBeneficiary;
    //primary fee applied to donations (base 10_000)(500 = 5%
    uint256 public primaryFee;
    IV3SwapRouter public swapRouter;
    Router02 public router02;

    TokenPoolChecker public poolchecker;
    IUSDT public usdt;
    WETH public weth;
    

    /* MULTI_SIG_CONFIG */
    address public signer1;
    address public signer2;
    address immutable public signerRecovery;
    mapping(address => bool) public signerRecoveryVotes;

    enum RequestType {
        PrimaryFeeChange,
        PrimaryBeneficiaryChange,
        AffiliateFeeChange,
        AffiliateRemoval,
        AffiliateGlobalFeeToggle,
        IndividualAffiliateFeeToggle,
        AffiliateWalletAddressChange
    }
    struct MultiSigRequest {
        address initiator;
        address newAddress;
        uint256 newFee;
        bytes32 affiliateID;
        bool requestActive;
        RequestType requestType;
    }

    MultiSigRequest public currentRequest;

    /* AFFILIATE_CONFIG */
    struct Affiliate{
        address receiver;
        uint256 feeAmount;
        bool feeEnabledInvidually;
        bytes32 affiliateID;
    }
    Affiliate[] affiliates;
    mapping(bytes32 => uint256) public affiliateIDtoIndex;
    mapping(bytes32 => bool) public affiliateIDexists;
    bool public isAffiliateFeeEnabled;
    /* */

    constructor(
        address payable _irouter,
        address _signer1,
        address _signer2,
        address _primaryBeneficiary,
        uint256 _primaryFee,
        address _weth,
        address _usdt,
        address payable _router02,
        address _poolchecker
    ){
        swapRouter = IV3SwapRouter(_irouter);
        isAffiliateFeeEnabled = false;
        signer1 = _signer1;
        signer2 = _signer2;
        signerRecovery = msg.sender;
        primaryBeneficiary = _primaryBeneficiary;
        primaryFee = _primaryFee;
        weth = WETH(_weth);
        usdt = IUSDT(_usdt);
        router02 = Router02(_router02);
        poolchecker = TokenPoolChecker(_poolchecker);
    }

    function enactPrimaryFee(uint256 _amountIn) public view returns(uint256 _amountDeducted, uint256 _totalOutAfterFee)
    {
        require(_amountIn > 0, "Amount must be greater than 0");
        uint256 divisor = 10_000;
        uint256 amountOutAfterFee = (_amountIn * (divisor - primaryFee)) / divisor;
        uint256 totalDeduction = (_amountIn - amountOutAfterFee);

        return (totalDeduction, amountOutAfterFee);
    }
    function enactSecondaryFee(uint256 _amountIn, bytes32 _affiliateID) public view returns(uint256 _amountDeducted, uint256 _totalOutAfterFee)
    {
        require(_amountIn > 0, "Amount must be greater than 0");
        uint256 divisor = 10_000;
        uint256 secondaryFee = affiliates[affiliateIDtoIndex[_affiliateID]].feeAmount;

        uint256 amountOutAfterFee = (_amountIn * (divisor - secondaryFee)) / divisor;
        uint256 totalDeduction = (_amountIn - amountOutAfterFee);

        return (totalDeduction , amountOutAfterFee);
    }

    function processTokenDonation(
        bytes32 _affiliateID,
        address _charity,
        uint256 _tokenAmount,
        address tokenAddress,
        uint24 _fee
        ) public payable nonReentrant whenNotPaused {
        require(_tokenAmount > 0, "Token amount must be greater than 0");
        require(_charity != address(0), "Invalid charity address");
        require(affiliateIDexists[_affiliateID], "Affiliate ID does not exist");

        uint256 amountWETH;

        (bool isPool, uint poolVersion) = poolchecker.isV2orV3(tokenAddress);
        safeTransferFrom(tokenAddress ,msg.sender, address(this), _tokenAmount); //tested

        if( isPool && poolVersion == 2){
            amountWETH = swapV2TokensForEth(tokenAddress, _tokenAmount, address(this));
        } else if ( isPool && poolVersion == 3){
            amountWETH = swapV3TokensForEth(tokenAddress, _tokenAmount, address(this), _fee);
        } else {
            revert("pool not found");
        }
        uint affIndex = affiliateIDtoIndex[_affiliateID];
        //get fee status for individual affiliate
        bool feeEnabledInvidually = affiliates[affIndex].feeEnabledInvidually;
        //always apply primary fee
        (uint256 primaryDeductionAmount, ) = enactPrimaryFee(amountWETH);
        //enum aff receiver
        address affReceiver = affiliates[affIndex].receiver;
        //init the deduction amount to 0 for readibility
        uint256 secondaryDeductionAmount = 0;
        //if affiliate fees enabled, enact second fee from the original msg.value
        if (isAffiliateFeeEnabled && feeEnabledInvidually) {
            (secondaryDeductionAmount, ) = enactSecondaryFee(amountWETH, _affiliateID);
        }
        //get total donation amount
        uint256 totalDonationToCharity = amountWETH - primaryDeductionAmount - secondaryDeductionAmount;
        //aprove WETH to deposit to unwrap WETH
        bool approveUnwrap = weth.approve(address(this), amountWETH);
        require(approveUnwrap, "Failed to approve WETH for unwrap");
        //unwrap WETH
        weth.withdraw(amountWETH);
        //transfer eth to their locations
        payable(_charity).transfer(totalDonationToCharity);
        payable(primaryBeneficiary).transfer(primaryDeductionAmount);
        //if secondaryDeductionAmount > 0, transfer to affiliate
        if (isAffiliateFeeEnabled && feeEnabledInvidually) {
            payable(affReceiver).transfer(secondaryDeductionAmount);
        }
        //emit event
        emit DonationProcessed(secondaryDeductionAmount, primaryDeductionAmount, totalDonationToCharity, msg.sender);
    }
    function swapV2TokensForEth(address _tokenAddress, uint256 _tokenAmountIn, address _recipient) internal returns(uint256) {
        safeApprove(_tokenAddress, address(router02), _tokenAmountIn);
        uint allowance = IERC20(_tokenAddress).allowance(address(this), address(router02));
        require(allowance >= _tokenAmountIn, "Failed to approve tokens for swap");

        address[] memory path = new address[](2);
        path[0] = _tokenAddress;
        path[1] = router02.WETH();

        // Get the estimated output amount
        uint[] memory amountsOut = router02.getAmountsOut(_tokenAmountIn, path);
        uint estimatedOutput = amountsOut[1];

        // Perform the swap
        router02.swapExactTokensForTokensSupportingFeeOnTransferTokens(
            _tokenAmountIn, 
            0, 
            path, 
            _recipient, 
            block.timestamp
        );

        return estimatedOutput; 
    }
    function swapV3TokensForEth(address _tokenAddress, uint256 _tokenAmountIn, address _recipient, uint24 _fee) internal returns(uint256 amountETH) {
        safeApprove(_tokenAddress, address(swapRouter), _tokenAmountIn);
        
        uint256 allowance = IERC20(_tokenAddress).allowance(address(this), address(swapRouter));
        require(allowance >= _tokenAmountIn, "Failed to approve tokens for swap");

        IV3SwapRouter.ExactInputSingleParams memory params = IV3SwapRouter.ExactInputSingleParams({
            tokenIn: _tokenAddress,
            tokenOut: 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2,
            fee: _fee,
            recipient: _recipient,
            amountIn: _tokenAmountIn,
            amountOutMinimum: 0,
            sqrtPriceLimitX96: 0
        });

        amountETH = swapRouter.exactInputSingle(params);
        return amountETH;
    }

    function processDonation(bytes32 _affiliateID, address _charity) public payable nonReentrant whenNotPaused{
        require(msg.value > 0, "value must be greater than 0 for msg.value");
        require(_charity != address(0), "invalid address");

        // Check if the affiliate ID exists
        require(affiliateIDexists[_affiliateID], "Affiliate ID does not exist");
        // Fee always active for primary
        (uint256 primaryDeductionAmount, ) = enactPrimaryFee(msg.value);
        //init the deduction amount to 0 for readibility
        uint256 secondaryDeductionAmount = 0;
        //get fee status for individual affiliate
        bool feeEnabledInvidually = affiliates[affiliateIDtoIndex[_affiliateID]].feeEnabledInvidually;
        // if affiliate fees enabled, enact second fee from the original msg.value
        if (isAffiliateFeeEnabled && feeEnabledInvidually) {
            (secondaryDeductionAmount, ) = enactSecondaryFee(msg.value, _affiliateID);
        }
        //get total donation amount
        uint256 totalDonation = msg.value - primaryDeductionAmount - secondaryDeductionAmount;
        uint256 remainingEthFromPrimaryAndSecondary = msg.value - totalDonation;
        //transfer eth to their locations
        payable(_charity).transfer(totalDonation);
        payable(primaryBeneficiary).transfer(primaryDeductionAmount);
        //if affiliate fees enabled, enact second fee from the original msg.value
        if (isAffiliateFeeEnabled && feeEnabledInvidually) {
            address affReceiver = affiliates[affiliateIDtoIndex[_affiliateID]].receiver;
            payable(affReceiver).transfer(secondaryDeductionAmount);
        }
        // Check if there are any remaining funds (due to rounding or other issues)
        uint256 remainingFunds = remainingEthFromPrimaryAndSecondary - primaryDeductionAmount - secondaryDeductionAmount;
        if (remainingFunds > 0) {
            payable(owner()).transfer(remainingFunds);
        }
        //emit event
        emit DonationProcessed(secondaryDeductionAmount, primaryDeductionAmount, totalDonation, msg.sender);
    }
    function addAffiliate(bytes32 _affiliateID, address _receiver, uint256 _feeAmount) internal {
        require(_affiliateID > 0, "Affiliate ID must be greater than 0");
        require(_receiver != address(0), "Receiver must be a valid address");
        require(_feeAmount <= 500, "Fee amount must be <= 500");
        
        uint256 newIndex = affiliates.length; // Get current length as the new index
        affiliates.push(Affiliate(_receiver, _feeAmount, true, _affiliateID));
        affiliateIDtoIndex[_affiliateID] = newIndex; // Set mapping to use newIndex

        emit AffiliateAdded(_receiver, _feeAmount);
    }

    function addManyAffiliates(
    bytes32[] memory _affiliateIDs,
    address[] memory _receivers,
    uint256[] memory _feeAmounts
    ) public onlyOwner {
        require(
            _affiliateIDs.length == _receivers.length && _receivers.length == _feeAmounts.length,
            "Data mis-matching"
        );

        for (uint256 i = 0; i < _affiliateIDs.length; i++) {
            require(affiliateIDtoIndex[_affiliateIDs[i]] == 0, "Affiliate ID already exists");
            require(_receivers[i] != address(0), "Receiver must be a valid address");
            require(_feeAmounts[i] <= 500, "Fee amount must be <= 500");

            uint256 newIndex = affiliates.length; // Get current length as the new index
            affiliates.push(Affiliate(_receivers[i], _feeAmounts[i], true, _affiliateIDs[i])); // Push new affiliate
            affiliateIDtoIndex[_affiliateIDs[i]] = newIndex; // Set mapping to use newIndex
            affiliateIDexists[_affiliateIDs[i]] = true;

            emit AffiliateAdded(_receivers[i], _feeAmounts[i]);
        }
    }

    function getAffiliateFee(bytes32 _affiliateID) public view returns (uint256 _feeAmount) {
        require(affiliateIDexists[_affiliateID], "Affiliate ID does not exist");
        uint256 index = affiliateIDtoIndex[_affiliateID];
        return affiliates[index].feeAmount;
    }
    function getAffiliateAddress(bytes32 _affiliateID) public view returns (address _affiliateAddress) {
        require(affiliateIDexists[_affiliateID], "Affiliate ID does not exist");
        uint256 index = affiliateIDtoIndex[_affiliateID];
        return affiliates[index].receiver;
    }
    function listAllAffiliates() public view returns (Affiliate[] memory) {
        return affiliates;
    }
    function getAffiliateCount() public view returns (uint256 _affiliateCount) {
        return affiliates.length;
    }
    modifier onlySigner {
        require(msg.sender == signer1 || msg.sender == signer2, "Must be a signer");
        _;
    }
    function updateRouterAddress(address _newRouter) public onlyOwner {
        swapRouter = IV3SwapRouter(_newRouter);
    }
    function updateWETHAddress(address _newWETH) public onlyOwner {
        weth = WETH(_newWETH);
    }
    /*CHANGE_PRIMARY_BENEFICIARY_CONFIG */
    event PrimaryBeneficiaryChangeRequested
    (
        address indexed initiator,
        address indexed newBeneficiary
    );
    event PrimaryBeneficiaryChangeApproved
    (
        address indexed initiator,
        address indexed newBeneficiary
    );
    function requestSetPrimaryBeneficiaryChange(address _newPrimary) public onlySigner requireInactiveRequest{
        currentRequest = MultiSigRequest({
            initiator: msg.sender,
            newAddress: _newPrimary,
            newFee: 0,
            affiliateID: 0,
            requestActive: true,
            requestType: RequestType.PrimaryBeneficiaryChange
        });
        emit PrimaryBeneficiaryChangeRequested(msg.sender, _newPrimary);
    }
    /* END_CHANGE_PRIMARY_BENEFICIARY_CONFIG */

    /* CHANGE_PRIMARY_FEE_CONFIG */
    event PrimaryFeeChangeRequested
    (
        address indexed initiator,
        uint256 indexed newFee
    );
    event PrimaryFeeChangeApproved
    (
        address indexed initiator,
        uint256 indexed newFee
    );
    function requestSetPrimaryFeeChange(uint256 _newFee) public onlySigner requireInactiveRequest {
        require(_newFee <= 3000 && _newFee >= 100,"cant raise fee over 30% or set below 1%");

        currentRequest = MultiSigRequest({
            initiator: msg.sender,
            newAddress: address(0),
            newFee: _newFee,
            affiliateID: 0,
            requestActive: true,
            requestType: RequestType.PrimaryFeeChange
        });
        emit PrimaryFeeChangeRequested(msg.sender, _newFee);
    }
    /* END_CHANGE_PRIMARY_FEE_CONFIG */

    /* CHANGE_AFFILIATE_FEE_CONFIG */
    event AffiliateFeeChangeRequested
    (
        address indexed initiator,
        uint256 indexed newFee,
        bytes32 indexed affiliateID
    );
    event AffiliateFeeChangeApproved
    (
        address indexed initiator,
        uint256 indexed newFee,
        bytes32 indexed affiliateID
    );
    function requestSetAffiliateFeeChange(uint256 _newFee, bytes32 _affiliateID) public onlySigner requireInactiveRequest {
        require(_newFee <= 500 && _newFee >= 100,"cant raise fee over 5% or set below 1%");
        require(affiliateIDexists[_affiliateID], "Affiliate ID does not exist");
       
        currentRequest = MultiSigRequest({
            initiator: msg.sender,
            newAddress: address(0),
            newFee: _newFee,
            affiliateID: _affiliateID,
            requestActive: true,
            requestType: RequestType.AffiliateFeeChange
        });
        emit AffiliateFeeChangeRequested(msg.sender, _newFee, _affiliateID);
    }
    /* END_CHANGE_AFFILIATE_FEE_CONFIG */

    /* AFFILIATE_REMOVAL_CONFIG */
    event AffiliateRemovalRequested
    (
        address indexed initiator,
        bytes32 indexed affiliateID
    );
    event AffiliateRemovalApproved
    (
        address indexed initiator,
        bytes32 indexed affiliateID
    );
    function requestAffiliateRemoval(bytes32 _affiliateID) public onlySigner requireInactiveRequest {
        require(affiliateIDexists[_affiliateID], "Affiliate ID does not exist");
    
        currentRequest = MultiSigRequest({
            initiator: msg.sender,
            newAddress: address(0),
            newFee: 0,
            affiliateID: _affiliateID,
            requestActive: true,
            requestType: RequestType.AffiliateRemoval
        });
        emit AffiliateRemovalRequested(msg.sender, _affiliateID);
    }
    /* END_AFFILIATE_REMOVAL_CONFIG */

    /* AFFILIATE_GLOBAL_FEE_TOGGLE_CONFIG */
    event AffiliateGlobalFeeToggleRequested
    (
        address indexed initiator,
        bool indexed isEnabled
    );
    event AffiliateGlobalFeeToggleApproved
    (
        address indexed initiator,
        bool indexed isEnabled
    );
    function requestAffiliateGlobalFeeToggle() public onlySigner requireInactiveRequest{
        
        currentRequest = MultiSigRequest({
            initiator: msg.sender,
            newAddress: address(0),
            newFee: 0,
            affiliateID: 0,
            requestActive: true,
            requestType: RequestType.AffiliateGlobalFeeToggle
        });
        emit AffiliateGlobalFeeToggleRequested(msg.sender, isAffiliateFeeEnabled);
    }
    /* TOGGLE_INDIVIDUAL_AFFILIATE_FEE_CONFIG */
    event IndividualAffiliateFeeToggleRequested(
        address indexed initiator,
        bool indexed isEnabled
    );
    event IndividualAffiliateFeeToggleApproved(
        address indexed initiator,
        bool indexed isEnabled
    );
    function requestIndividualAffiliateFeeToggle(bytes32 _affiliateID) public onlySigner requireInactiveRequest {
        currentRequest = MultiSigRequest({
            initiator: msg.sender,
            newAddress: address(0),
            newFee: 0,
            affiliateID: _affiliateID,
            requestActive: true,
            requestType: RequestType.IndividualAffiliateFeeToggle
        });
        emit IndividualAffiliateFeeToggleRequested(msg.sender, affiliates[affiliateIDtoIndex[_affiliateID]].feeEnabledInvidually);
    }
    event AffiliateWalletAddressChangeRequested(
        address indexed initiator,
        address indexed newAddress,
        bytes32 indexed affiliateID
    );
    event AffiliateWalletAddressChangeApproved(
        address indexed initiator,
        address indexed newAddress,
        bytes32 indexed affiliateID
    );
    function requestAffiliateWalletAddressChange(address _newAddress, bytes32 _affiliateID) public onlySigner requireInactiveRequest {
        require(affiliateIDexists[_affiliateID], "Affiliate ID does not exist");
        currentRequest = MultiSigRequest({
            initiator: msg.sender,
            newAddress: _newAddress,
            newFee: 0,
            affiliateID: _affiliateID,
            requestActive: true,
            requestType: RequestType.AffiliateWalletAddressChange
        });
        emit AffiliateWalletAddressChangeRequested(msg.sender, _newAddress, _affiliateID);
    }
    /* END_AFFILIATE_GLOBAL_FEE_TOGGLE_CONFIG */
    error InvalidRequestType(RequestType requestType);
    function _approveRequest() public onlySigner {
        require(currentRequest.requestActive, "No active request");
        require(msg.sender != currentRequest.initiator, "the other signer must complete the transaction");

        if (currentRequest.requestType == RequestType.PrimaryBeneficiaryChange) {
            primaryBeneficiary = currentRequest.newAddress;
            emit PrimaryBeneficiaryChangeApproved(currentRequest.initiator, currentRequest.newAddress);
        } 
        else if (currentRequest.requestType == RequestType.PrimaryFeeChange) {
            primaryFee = currentRequest.newFee;
            emit PrimaryFeeChangeApproved(currentRequest.initiator, currentRequest.newFee);
        } 
        else if (currentRequest.requestType == RequestType.AffiliateFeeChange) {
            bytes32 _affiliateID = currentRequest.affiliateID;
            //get the index of the affiliate struct from the affiliateID
            uint256 indexToChange = affiliateIDtoIndex[_affiliateID];
            //set the new fee
            affiliates[indexToChange].feeAmount = currentRequest.newFee;
            emit AffiliateFeeChangeApproved(currentRequest.initiator, currentRequest.newFee, currentRequest.affiliateID);
        } 
        else if (currentRequest.requestType == RequestType.AffiliateRemoval) {
            //enum the affiliateID
            bytes32 _affiliateID = currentRequest.affiliateID;
            //get the index of the affiliate struct from the affiliateID
            uint256 indexToRemove = affiliateIDtoIndex[_affiliateID];
            //enumerate the last affiliate in the array
            uint256 lastIndex = affiliates.length - 1;
            //get the affiliateID of the last affiliate in the array
            bytes32 lastAffiliateID = getAffiliateID(affiliates[lastIndex]);
            // Move the last element to the spot of the one to remove
            affiliates[indexToRemove] = affiliates[lastIndex];
            // Update the mapping to point to the new indexA
            affiliateIDtoIndex[lastAffiliateID] = indexToRemove;
            // Delete the last element and reduce the array size
            affiliates.pop();
            // Remove the affiliate ID from the mapping
            delete affiliateIDtoIndex[_affiliateID];
            // set existence to false
            affiliateIDexists[_affiliateID] = false;
            emit AffiliateRemovalApproved(currentRequest.initiator, currentRequest.affiliateID);
        } 
        else if (currentRequest.requestType == RequestType.AffiliateGlobalFeeToggle) {
            isAffiliateFeeEnabled = !isAffiliateFeeEnabled;
            emit AffiliateGlobalFeeToggleApproved(currentRequest.initiator, isAffiliateFeeEnabled);
        }
        else if (currentRequest.requestType == RequestType.IndividualAffiliateFeeToggle) {
            bytes32 _affiliateID = currentRequest.affiliateID;
            //get the index of the affiliate struct from the affiliateID
            uint256 indexToChange = affiliateIDtoIndex[_affiliateID];
            //set the new fee
            affiliates[indexToChange].feeEnabledInvidually = !affiliates[indexToChange].feeEnabledInvidually;
            emit IndividualAffiliateFeeToggleApproved(currentRequest.initiator, affiliates[indexToChange].feeEnabledInvidually);
        }
        else if(currentRequest.requestType == RequestType.AffiliateWalletAddressChange){
            bytes32 _affiliateID = currentRequest.affiliateID;
            //get the index of the affiliate struct from the affiliateID
            uint256 indexToChange = affiliateIDtoIndex[_affiliateID];
            //set the new fee
            affiliates[indexToChange].receiver = currentRequest.newAddress;
            emit AffiliateWalletAddressChangeApproved(currentRequest.initiator, currentRequest.newAddress, currentRequest.affiliateID);
        }
        else {
            revert InvalidRequestType(currentRequest.requestType);
        }
        // Reset the request to indicate that it has been processed
        delete currentRequest;
    }
    /*AFFILIATE_HELPER_FUNCTIONS */
    function getAffiliateID(Affiliate memory affiliate) internal pure returns (bytes32){
        return affiliate.affiliateID;
    }
    function getCurrentRequest() public view returns (MultiSigRequest memory){
        return currentRequest;
    }
    function getCurrentRequestType() public view returns (RequestType){
        return currentRequest.requestType;
    }
    function getCurrentRequestInitiator() public view returns (address){
        return currentRequest.initiator;
    }
    function getIndividualAffiliateFeeStatus(bytes32 _affiliateID) public view returns (bool){
        return affiliates[affiliateIDtoIndex[_affiliateID]].feeEnabledInvidually;
    }
    function pause() public onlyOwner {
        _pause();
    }
    function unpause() public onlyOwner {
        _unpause();
    }
    address private ownerRequest;
    //override transferOwnership from ownable to allow for multi sig recovery
    function transferOwnership(address newOwner) public override onlySigner {
        require(newOwner != address(0), "Ownable: new owner cannot be the zero address");

        // Only update if no votes have been cast yet
        if(!ownerRecoveryVotes[signer1] && !ownerRecoveryVotes[signer2]) {
            ownerRequest = newOwner;
        }

        require(ownerRequest == newOwner, "Address not matching request. Signers must agree to new owner address");

        ownerRecoveryVotes[msg.sender] = true;

        // Check if both signers have agreed
        if(ownerRecoveryVotes[signer1] && ownerRecoveryVotes[signer2]) {
            _transferOwnership(newOwner);

            // Reset the state
            ownerRecoveryVotes[signer1] = false;
            ownerRecoveryVotes[signer2] = false;
            ownerRequest = address(0);
        }
    }
    /* END_AFFILIATE_HELPER_FUNCTIONS */
    mapping(address => bool) ownerRecoveryVotes;

    modifier onlyRecoveryAndSigners {
        require(msg.sender == signerRecovery || msg.sender == signer1 || msg.sender == signer2, "Must be a signer or recovery");
        _;
    }
    modifier requireInactiveRequest {
        require(currentRequest.requestActive == false, "request already exists");
        _;
    }
    /* RECOVER_FROM_COMPROMISED_SIGNER */
    event SingerRecovered(
        address indexed newSigner,
        address indexed lostSigner
    );
    function recoverLostDelegate(address _newSigner) public onlyRecoveryAndSigners{
        //for each call map address to true
        signerRecoveryVotes[msg.sender] = true;
        //if any 2 of 3 votes are true, reset signers
        if(
            signerRecoveryVotes[signer1] && signerRecoveryVotes[signer2] ||
            signerRecoveryVotes[signer1] && signerRecoveryVotes[signerRecovery] ||
            signerRecoveryVotes[signer2] && signerRecoveryVotes[signerRecovery]
        ){
            //determine which signer has not voted
            // if signer1 has not voted we will assume they are the lost delegate
            if(!signerRecoveryVotes[signer1]){
                signer1 = _newSigner;
                emit SingerRecovered(_newSigner, signer1);
            }
            //else if signer2 has not voted we will assume they are the lost delegate
            else if(!signerRecoveryVotes[signer2]){
                signer2 = _newSigner;
                emit SingerRecovered(_newSigner, signer2);
            }

            //reset votes
            signerRecoveryVotes[signer1] = false;
            signerRecoveryVotes[signer2] = false;
            signerRecoveryVotes[signerRecovery] = false;
        }
        
    }
    /* END_RECOVER_FROM_COMPROMISED_SIGNER */

    receive() payable external {
        // Ensure that only the contract itself can send ETH (if that's the intended behavior)
        require(msg.sender == address(this) || msg.sender == address(weth), "Unauthorized sender");
        // Emit an event to log that ETH was received
        emit EthReceived(msg.sender, msg.value);
    }

    //by logic in contract this should never be able to be used. but in case of emergency and ETH is stuck in contract. this will allow the owner to withdraw it safely and transparently.
    function rescueETHFromContract() public onlyOwner {
        payable(owner()).transfer(address(this).balance);
    }
    //by logic in contract this should never be able to be used. but in case of emergency and ERC20 is stuck in contract. this will allow the owner to withdraw it safely and transparently.
    function rescueERC20TokenFromContract(address _tokenAddress) public onlyOwner {
        bool transfer = IERC20(_tokenAddress).transfer(owner(), IERC20(_tokenAddress).balanceOf(address(this)));
        require(transfer, "Failed to transfer tokens");
    }
    event EthReceived(address indexed sender, uint256 amount);
    event DonationProcessed
    (
        uint256 affiliateTake,
        uint256 primaryTake,
        uint256 totalDonation,
        address sender
    );
    event AffiliateAdded
    (
        address receiver,
        uint256 feeAmount
    );
    event AffiliateFeeToggled
    (
        bool isEnabled
    );
    event AffiliateFeeChanged
    (
        uint256 affiliateID,
        uint256 newFee
    ); 
    event PrimaryFeeChanged
    (
        uint256 newFee
    );
    address public USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;

    function changeUSDTaddress(address _newUSDT) public onlyOwner {
        require(_newUSDT != address(0), "Invalid address");
        USDT = _newUSDT;
    }
    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        if(token == USDT) {
            usdt.transferFrom(from, to, value);
        } else {
            (bool success, bytes memory data) =
                token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
            require(success, "STF: transferFrom failed");

            // If data has returned and it's not true, revert
            if (data.length > 0) {
                require(data.length == 32, "STF: data size should be 32 bytes");
                bool returnValue = abi.decode(data, (bool));
                require(returnValue, "STF: transferFrom did not return true");
            }
        }
    }
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        if(token == USDT) {
            usdt.approve(to, value);
        } else {
            (bool success, bytes memory data) = 
                token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
            require(success, "SA: approve call failed");

            if (data.length > 0) {
                require(data.length == 32, "SA: data size should be 32 bytes");
                bool returnValue = abi.decode(data, (bool));
                require(returnValue, "SA: approve did not return true");
            }
        }
    }


}
// File: contracts/IRouter02.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.17;

interface Router02 {
    function WETH() external view returns (address);
    function getAmountsOut(uint256 amountIn, address[] memory path)
        external
        view
        returns (uint256[] memory amounts);
    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] memory path,
        address to,
        uint256 deadline
    ) external;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] memory path,
        address to,
        uint256 deadline
    ) external;


    receive() external payable;
}

// File: contracts/IUSDT.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.17;

interface IUSDT {
    function approve(address _spender, uint256 _value) external;
    function transferFrom(
        address _from,
        address _to,
        uint256 _value
    ) external;
    function allowance(address _owner, address _spender)
        external
        view
        returns (uint256 remaining);
}
// File: contracts/IV3Router.sol



// SPDX-License-Identifier: UNLICENSED
// !! THIS FILE WAS AUTOGENERATED BY abi-to-sol v0.8.0. SEE SOURCE BELOW. !!
pragma solidity ^0.8.17;

interface IV3SwapRouter {
   
    function exactInputSingle(
        IV3SwapRouter.ExactInputSingleParams memory params
    ) external payable returns (uint256 amountOut);

    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

}
// File: contracts/IWETH.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.17;

interface WETH {

    function approve(address guy, uint256 wad) external returns (bool);

    function withdraw(uint256 wad) external;

    function transfer(address dst, uint256 wad) external returns (bool);

    function deposit() external payable;



    event Approval(address indexed src, address indexed guy, uint256 wad);
    event Deposit(address indexed dst, uint256 wad);
    event Withdrawal(address indexed src, uint256 wad);
}
// File: contracts/poolchecker.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

interface IUniswapV2Factory {
    function getPair(address tokenA, address tokenB) external view returns (address pair);
}

interface IUniswapV2Pair {
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
}

interface IUniswapV3Factory {
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
}

interface IUniswapV3Pool {
    function liquidity() external view returns (uint256);
}

import "@openzeppelin/contracts/access/Ownable.sol";

contract TokenPoolChecker is Ownable{
    address public UNISWAP_V2_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
    address public UNISWAP_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984; 
    address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH address

    uint24[] public feeTiers = [500, 3000, 10000];

    function isV2orV3(address token) public view returns (bool, uint) {
        bool isV2 = hasLiquidityV2(token);
        bool isV3 = hasLiquidityV3(token);

        if (isV2 && isV3) {
            uint256 v2Liquidity = getV2Liquidity(token);
            uint256 v3Liquidity = getV3Liquidity(token);
            
            // Return the pool with higher liquidity
            if (v2Liquidity > v3Liquidity) {
                return (true, 2); // Prefer V2
            } else {
                return (true, 3); // Prefer V3
            }
        } else if (isV2) {
            return (true, 2); // Only V2 is available
        } else if (isV3) {
            return (true, 3); // Only V3 is available
        } else {
            return (false, 0); // No pool available
        }
    }


    function hasLiquidityV2(address token) public view returns (bool) {
        IUniswapV2Factory factoryV2 = IUniswapV2Factory(UNISWAP_V2_FACTORY);
        address pair = factoryV2.getPair(token, WETH);
        return pair != address(0);
    }

    function hasLiquidityV3(address token) public view returns (bool) {
        IUniswapV3Factory factoryV3 = IUniswapV3Factory(UNISWAP_V3_FACTORY);
        for (uint i = 0; i < feeTiers.length; i++) {
            address pool = factoryV3.getPool(token, WETH, feeTiers[i]);
            
            if (pool != address(0)) {
                return true;
            }
        }
        return false;
    }

    function preferredPool(address token) public view returns (uint) {
        (bool isPool, uint poolVersion) = isV2orV3(token);

        if (!isPool) return 0; // No pool available

        if (poolVersion == 3) {
            uint256 v2Liquidity = getV2Liquidity(token);
            uint256 v3Liquidity = getV3Liquidity(token);

            // Compare v2 and v3 liquidity and return the preferred version
            if (v2Liquidity > v3Liquidity) {
                return 2; // Prefer V2
            } else {
                return 3; // Prefer V3
            }
        } else {
            return poolVersion; // Only one version is available
        }
    }

    function getV2Liquidity(address token) public view returns (uint256) {
        IUniswapV2Pair pair = IUniswapV2Pair(IUniswapV2Factory(UNISWAP_V2_FACTORY).getPair(token, WETH));
        (uint256 reserve0, uint256 reserve1,) = pair.getReserves();
        return token < WETH ? reserve0 : reserve1;
    }

    function getV3Liquidity(address token) public view returns (uint256) {
        uint256 totalLiquidity = 0;
        IUniswapV3Factory factoryV3 = IUniswapV3Factory(UNISWAP_V3_FACTORY);
        for (uint i = 0; i < feeTiers.length; i++) {
            address poolAddress = factoryV3.getPool(token, WETH, feeTiers[i]);
            if (poolAddress != address(0)) {
                IUniswapV3Pool pool = IUniswapV3Pool(poolAddress);
                totalLiquidity += pool.liquidity();
            }
        }
        return totalLiquidity;
    }

    function updateUniswapV2Factory(address _uniswapV2Factory) public onlyOwner {
        UNISWAP_V2_FACTORY = _uniswapV2Factory;
    }
    function updateUniswapV3Factory(address _uniswapV3Factory) public onlyOwner {
        UNISWAP_V3_FACTORY = _uniswapV3Factory;
    }
}