// 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";


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;
    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
    ){
        swapRouter = IV3SwapRouter(_irouter);
        isAffiliateFeeEnabled = false;
        signer1 = _signer1;
        signer2 = _signer2;
        signerRecovery = msg.sender;
        primaryBeneficiary = _primaryBeneficiary;
        primaryFee = _primaryFee;
        weth = WETH(_weth);
    }

    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");

        bool transfer = IERC20(tokenAddress).transferFrom(msg.sender, address(this), _tokenAmount); //tested
        require(transfer, "Failed to transfer tokens");

        uint256 amountWETH = swapTokensForEth(tokenAddress, _tokenAmount, address(this), _fee); //tested
        //get fee status for individual affiliate
        bool feeEnabledInvidually = affiliates[affiliateIDtoIndex[_affiliateID]].feeEnabledInvidually;
        //always apply primary fee
        (uint256 primaryDeductionAmount, ) = enactPrimaryFee(amountWETH);
        //enum aff receiver
        address affReceiver = affiliates[affiliateIDtoIndex[_affiliateID]].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 swapTokensForEth(address _tokenAddress, uint256 _tokenAmountIn, address _recipient, uint24 _fee) internal returns(uint256 amountETH) {
        bool approval = IERC20(_tokenAddress).approve(address(swapRouter), _tokenAmountIn);
        require(approval, "Failed to approve tokens for swap");
        
        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
    ); 

}
// 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);
}