Skip to content
Verified contractExactMIT

PaymentFactory

Address0x1e73fdba5690fce7707bfff187e7863320835cd3
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.19

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.19+commit.7dd6d404
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,294,525
Creation transaction
0x15af971fb0…b54d479a25

45 files

contracts/payment-factory/PaymentFactory.sol

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

import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts/proxy/Clones.sol";
import "./interfaces/IPaymentContract.sol";
import "./templates/SimpleHRDevContract.sol";
import "./templates/EscrowContractV2.sol";
import "./templates/FlexiblePaymentSplit.sol";
import "./TreasuryManager.sol";
import "./MembershipManager.sol";

/**
 * @title PaymentFactory
 * @notice Factory contract for creating payment distribution contracts
 * @dev Creates payment contracts based on templates with customizable recipients and fee distributions
 */
contract PaymentFactory is Initializable, AccessControlUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable, UUPSUpgradeable {
    using SafeERC20Upgradeable for IERC20Upgradeable;

    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
    bytes32 public constant TEMPLATE_MANAGER_ROLE = keccak256("TEMPLATE_MANAGER_ROLE");

    // Contract template types
    enum ContractType {
        HR_DEV_SIMPLE,      // Simple HR -> Developer payment (2% platform fee)
        ESCROW,             // Escrow with milestone payments (2% platform + 3% HR)
        FLEXIBLE_SPLIT      // Flexible payment split with multiple recipients (1% platform fee)
        // SUBSCRIPTION,    // Recurring payments (TODO)
        // PROJECT_BASED    // Project-based payments with stages (TODO)
    }

    struct ContractTemplate {
        string name;
        string description;
        uint256 platformFeePercent;    // Basis points (100 = 1%)
        uint256 minRecipients;
        uint256 maxRecipients;
        bool active;
        address implementationAddress;
    }

    struct PaymentContractInfo {
        address contractAddress;
        ContractType contractType;
        address creator;
        address[] recipients;
        uint256[] shares;              // Basis points
        uint256 platformFee;           // Basis points
        uint256 createdAt;
        bool active;
    }

    // State variables
    mapping(ContractType => ContractTemplate) public templates;
    mapping(address => PaymentContractInfo) public paymentContracts;
    address[] public allPaymentContracts;
    mapping(address => address[]) private contractsByUser;  // user => their contracts
    
    // Platform settings
    address public platformTreasury; // TreasuryManager contract address
    TreasuryManager public treasuryManager;
    MembershipManager public membershipManager;
    bool public membershipRequired = false; // Toggle for requiring membership
    uint256 public defaultPlatformFee = 200; // 2% default
    uint256 public maxPlatformFee = 1000;    // 10% max
    uint256 public contractCreationFee = 0;  // Fee to recover from first payment (0 = disabled)
    bool public creationFeeEnabled = false;  // Whether to charge creation fee
    address public escrowAdmin; // Admin for escrow dispute resolution
    
    // Events
    event TemplateAdded(ContractType indexed contractType, string name, address implementation);
    event TemplateUpdated(ContractType indexed contractType, bool active);
    event PaymentContractCreated(
        address indexed contractAddress,
        ContractType indexed contractType,
        address indexed creator,
        address[] recipients,
        uint256[] shares
    );
    event PlatformTreasuryUpdated(address oldTreasury, address newTreasury);
    event PlatformFeeUpdated(uint256 oldFee, uint256 newFee);
    event CreationFeeUpdated(uint256 oldFee, uint256 newFee);
    event CreationFeeSet(address indexed contractAddress, uint256 fee);
    event CreationFeePaid(address indexed payer, address indexed contractAddress, uint256 fee, bool immediate);
    event MembershipManagerUpdated(address indexed oldManager, address indexed newManager);
    event MembershipRequirementUpdated(bool required);
    event EscrowAdminUpdated(address indexed oldAdmin, address indexed newAdmin);

    constructor() {
        _disableInitializers();
    }

    /**
     * @notice Initialize upgradeable PaymentFactory
     * @param _platformTreasury TreasuryManager contract address
     * @param _admin Admin address to receive roles
     */
    function initialize(address _platformTreasury, address _admin) external initializer {
        require(_platformTreasury != address(0), "Invalid treasury address");
        require(_admin != address(0), "Invalid admin address");

        __AccessControl_init();
        __ReentrancyGuard_init();
        __Pausable_init();
        
        _grantRole(DEFAULT_ADMIN_ROLE, _admin);
        _grantRole(ADMIN_ROLE, _admin);
        _grantRole(TEMPLATE_MANAGER_ROLE, _admin);
        
        platformTreasury = _platformTreasury;
        treasuryManager = TreasuryManager(_platformTreasury);
        escrowAdmin = _admin; // Initially set admin
        
        _initializeTemplates();
    }

    /**
     * @notice Initialize default contract templates
     */
    function _initializeTemplates() internal {
        // HR-Dev Simple Contract
        templates[ContractType.HR_DEV_SIMPLE] = ContractTemplate({
            name: "HR-Developer Payment",
            description: "Simple payment contract between HR and Developer with 2% platform fee",
            platformFeePercent: 200, // 2%
            minRecipients: 3,
            maxRecipients: 3,
            active: true,
            implementationAddress: address(0) // Will be set after deployment
        });
        
        // Escrow Contract
        templates[ContractType.ESCROW] = ContractTemplate({
            name: "Milestone-based Escrow",
            description: "Escrow contract with milestone payments, 2% platform + 3% HR fee",
            platformFeePercent: 500, // 5% (2% platform + 3% HR)
            minRecipients: 3,
            maxRecipients: 3,
            active: true,
            implementationAddress: address(0) // Will be set after deployment
        });

        // Flexible Payment Split
        templates[ContractType.FLEXIBLE_SPLIT] = ContractTemplate({
            name: "Flexible Payment Split",
            description: "Flexible payment splitting with custom recipients, 1% platform fee",
            platformFeePercent: 100, // 1%
            minRecipients: 1,
            maxRecipients: 50,
            active: true,
            implementationAddress: address(0) // Will be set after deployment
        });
    }

    /**
     * @notice Create new payment contract from template
     * @param _contractType Type of contract template to use
     * @param _recipients Array of recipient addresses
     * @param _shares Array of shares in basis points (must sum to 10000 - platform fee)
     * @param _paymentToken Token to use for payments (address(0) for ETH)
     * @param _customParams Custom parameters specific to contract type
     * @param _payNow If true, pay creation fee immediately; if false, deduct from first payment
     * @param _referrer Referrer address (address(0) if no referrer)
     * @param _partner Partner address (address(0) if no partner)
     */
    function createPaymentContract(
        ContractType _contractType,
        address[] memory _recipients,
        uint256[] memory _shares,
        address _paymentToken,
        bytes memory _customParams,
        bool _payNow,
        address _referrer,
        address _partner
    ) external payable nonReentrant whenNotPaused returns (address) {
        // Check membership requirement if enabled
        if (membershipRequired && address(membershipManager) != address(0)) {
            require(
                membershipManager.hasActiveSubscription(msg.sender),
                "Active subscription required"
            );
        }
        
        ContractTemplate storage template = templates[_contractType];
        require(template.active, "Template not active");
        require(template.implementationAddress != address(0), "Template implementation not set");
        require(_recipients.length == _shares.length, "Recipients and shares length mismatch");
        require(_recipients.length >= template.minRecipients, "Too few recipients");
        require(_recipients.length <= template.maxRecipients, "Too many recipients");

        // Validate shares sum
        uint256 totalShares = 0;
        for (uint256 i = 0; i < _shares.length; i++) {
            // For HR_DEV_SIMPLE, allow address(0) for client (first recipient) to enable anyone-can-pay.
            // (Escrow v2 recipients are its payees; the client comes in _customParams.)
            if (_contractType == ContractType.HR_DEV_SIMPLE && i == 0) {
                // Client can be address(0) - means anyone can pay
                // Skip address validation for first recipient
            } else {
                require(_recipients[i] != address(0), "Invalid recipient address");
            }
            require(_shares[i] > 0, "Share must be greater than 0");
            totalShares += _shares[i];
        }
        
        // For FLEXIBLE_SPLIT, shares must sum to 10000 (100%)
        // For other templates, shares must sum to (10000 - platform fee)
        uint256 expectedTotal;
        if (_contractType == ContractType.FLEXIBLE_SPLIT || _contractType == ContractType.ESCROW) {
            expectedTotal = 10000; // 100% - the contract takes the platform fee itself (Escrow v2: template.platformFeePercent)
        } else {
            expectedTotal = 10000 - template.platformFeePercent;
        }
        require(totalShares == expectedTotal, "Shares must sum to expected total");

        // Handle creation fee payment if enabled
        if (creationFeeEnabled && contractCreationFee > 0) {
            if (_payNow) {
                // Client pays creation fee immediately and forwards to TreasuryManager
                if (_paymentToken == address(0)) {
                    // ETH payment not supported for TreasuryManager (use stablecoin)
                    revert("Use stablecoin for creation fee");
                } else {
                    // ERC20 payment - transfer to this contract first, then approve TreasuryManager
                    IERC20Upgradeable(_paymentToken).safeTransferFrom(msg.sender, address(this), contractCreationFee);
                    IERC20Upgradeable(_paymentToken).safeApprove(address(treasuryManager), contractCreationFee);
                    treasuryManager.receiveFunds(contractCreationFee, "creation_fee");
                }
                emit CreationFeePaid(msg.sender, address(0), contractCreationFee, true);
            } else {
                // Fee will be deducted from first payment
                require(msg.value == 0, "Do not send ETH if paying later");
            }
        } else {
            require(msg.value == 0, "Creation fee not enabled");
        }

        // Create new contract instance
        address newContract = _deployContract(_contractType, _recipients, _shares, _paymentToken, _customParams, _referrer, _partner, _payNow);
        
        // Set creation fee if enabled and client chose to pay later
        if (creationFeeEnabled && contractCreationFee > 0 && !_payNow) {
            if (_contractType == ContractType.HR_DEV_SIMPLE) {
                SimpleHRDevContract(payable(newContract)).setCreationFee(contractCreationFee);
            } else if (_contractType == ContractType.ESCROW) {
                EscrowContractV2(newContract).setCreationFee(contractCreationFee);
            }
            emit CreationFeeSet(newContract, contractCreationFee);
            emit CreationFeePaid(msg.sender, newContract, contractCreationFee, false);
        }
        
        // Store contract info
        paymentContracts[newContract] = PaymentContractInfo({
            contractAddress: newContract,
            contractType: _contractType,
            creator: msg.sender,
            recipients: _recipients,
            shares: _shares,
            platformFee: template.platformFeePercent,
            createdAt: block.timestamp,
            active: true
        });
        
        allPaymentContracts.push(newContract);
        contractsByUser[msg.sender].push(newContract);
        
        // Also add contract to recipients' lists (HR and Developer)
        for (uint256 i = 0; i < _recipients.length; i++) {
            if (_recipients[i] != msg.sender) {
                contractsByUser[_recipients[i]].push(newContract);
            }
        }

        // FlexiblePaymentSplit / Escrow v2: also add to the client's list if the client is not creator or recipient
        if (_contractType == ContractType.FLEXIBLE_SPLIT || _contractType == ContractType.ESCROW) {
            address clientAddress = _contractType == ContractType.ESCROW
                ? EscrowContractV2(newContract).client()
                : FlexiblePaymentSplit(newContract).client();
            
            // Check if client is not already in the list (not creator and not recipient)
            bool clientAlreadyAdded = (clientAddress == msg.sender);
            if (!clientAlreadyAdded) {
                for (uint256 i = 0; i < _recipients.length; i++) {
                    if (_recipients[i] == clientAddress) {
                        clientAlreadyAdded = true;
                        break;
                    }
                }
            }
            
            // Add client to contractsByUser if not already added
            if (!clientAlreadyAdded) {
                contractsByUser[clientAddress].push(newContract);
            }
        }

        emit PaymentContractCreated(newContract, _contractType, msg.sender, _recipients, _shares);
        
        return newContract;
    }

    /**
     * @notice Deploy contract based on type
     */
    function _deployContract(
        ContractType _contractType,
        address[] memory _recipients,
        uint256[] memory _shares,
        address _paymentToken,
        bytes memory _customParams,
        address _referrer,
        address _partner,
        bool _payNow
    ) internal returns (address) {
        if (_contractType == ContractType.HR_DEV_SIMPLE) {
            require(_recipients.length == 3, "HR-Dev contract requires exactly 3 recipients (client, HR, developer)");
            
            // Get implementation address from template
            address implementation = templates[_contractType].implementationAddress;
            require(implementation != address(0), "Implementation not set");
            
            // Create clone using EIP-1167
            address clone = Clones.clone(implementation);
            
            // Initialize the clone
            SimpleHRDevContract(payable(clone)).initialize(
                _recipients[0], // Client (can be address(0) if anyone can pay)
                _recipients[1], // HR
                _recipients[2], // Developer
                _shares[1],     // HR share (ignored, using fixed 3%)
                _shares[2],     // Developer share (ignored, using fixed 95%)
                200,            // Platform fee (ignored)
                platformTreasury,
                _paymentToken,
                _referrer,      // Referrer address
                _partner,       // Partner address
                address(membershipManager) // Membership manager for refunds
            );
            
            // Add partner to contractsByUser if exists
            if (_partner != address(0)) {
                bool partnerAlreadyAdded = (_partner == msg.sender);
                if (!partnerAlreadyAdded) {
                    for (uint256 i = 0; i < _recipients.length; i++) {
                        if (_recipients[i] == _partner) {
                            partnerAlreadyAdded = true;
                            break;
                        }
                    }
                }
                if (!partnerAlreadyAdded) {
                    contractsByUser[_partner].push(clone);
                }
            }
            
            // Add referrer to contractsByUser if exists
            if (_referrer != address(0)) {
                bool referrerAlreadyAdded = (_referrer == msg.sender);
                if (!referrerAlreadyAdded) {
                    for (uint256 i = 0; i < _recipients.length; i++) {
                        if (_recipients[i] == _referrer) {
                            referrerAlreadyAdded = true;
                            break;
                        }
                    }
                }
                if (!referrerAlreadyAdded && _referrer != _partner) {
                    contractsByUser[_referrer].push(clone);
                }
            }
            
            return clone;
        }
        
        if (_contractType == ContractType.ESCROW) {
            // Escrow v2: _recipients/_shares are the payees (shares sum to 100%, checked above and in initialize).
            // _customParams = abi.encode(client, developer, projectName, projectDescription); the developer (work
            // executor) must be one of the payees. Referrer/partner aren't used by v2 - pay them as payees instead.
            address implementation = templates[_contractType].implementationAddress;
            require(implementation != address(0), "Implementation not set");
            require(_customParams.length > 0, "Escrow needs client, developer and project info");
            (address escrowClient, address escrowDeveloper, string memory projectName, string memory projectDescription) =
                abi.decode(_customParams, (address, address, string, string));

            address clone = Clones.clone(implementation);
            EscrowContractV2(clone).initialize(
                EscrowContractV2.InitParams({
                    client: escrowClient,
                    developer: escrowDeveloper,
                    platformTreasury: platformTreasury,
                    paymentToken: _paymentToken,
                    admin: escrowAdmin,
                    platformFeeBps: templates[_contractType].platformFeePercent,
                    projectName: projectName,
                    projectDescription: projectDescription
                }),
                _recipients,
                _shares
            );

            return clone;
        }

        if (_contractType == ContractType.FLEXIBLE_SPLIT) {
            require(_recipients.length >= 1, "Flexible Split requires at least 1 recipient");
            
            // Get implementation address from template
            address implementation = templates[_contractType].implementationAddress;
            require(implementation != address(0), "Implementation not set");
            
            // Decode custom params for client address and distribution mode
            address clientAddress = msg.sender; // Default: creator is client
            FlexiblePaymentSplit.DistributionMode distributionMode = FlexiblePaymentSplit.DistributionMode.DIRECT_TRANSFER;
            
            if (_customParams.length > 0) {
                (clientAddress, distributionMode) = abi.decode(_customParams, (address, FlexiblePaymentSplit.DistributionMode));
            }
            
            // Pass the _payNow flag from createPaymentContract
            // If true, Factory already paid the fee to Treasury
            // If false, fee will be deducted from first payment
            bool payCreationFeeNow = _payNow && creationFeeEnabled && contractCreationFee > 0;
            
            // Create clone using EIP-1167
            address clone = Clones.clone(implementation);
            
            // Initialize the clone with struct
            FlexiblePaymentSplit(clone).initialize(
                FlexiblePaymentSplit.InitParams({
                    client: clientAddress,
                    paymentToken: _paymentToken,
                    treasury: platformTreasury,
                    mode: distributionMode,
                    creationFee: creationFeeEnabled ? contractCreationFee : 0,
                    payCreationFeeNow: payCreationFeeNow
                }),
                _recipients,
                _shares
            );
            
            return clone;
        }
        
        revert("Unknown contract type");
    }

    /**
     * @notice Set implementation address for a template
     * @dev Used after deploying the master contract
     */
    function setTemplateImplementation(
        ContractType _contractType,
        address _implementationAddress
    ) external onlyRole(ADMIN_ROLE) {
        require(_implementationAddress != address(0), "Invalid implementation address");
        require(_implementationAddress.code.length > 0, "Implementation must be a contract");
        templates[_contractType].implementationAddress = _implementationAddress;
        emit TemplateAdded(_contractType, templates[_contractType].name, _implementationAddress);
    }

    /// @notice Hard ceiling for a template's platform fee (10%). A constant, so it takes no storage slot.
    uint256 public constant MAX_TEMPLATE_PLATFORM_FEE = 1000;

    /**
     * @notice Change a template's platform fee and recipient limits (e.g. Escrow v2's fee, which its clones read
     *         at creation). addTemplate can't do this on the Mainnet proxy: maxPlatformFee was never initialised
     *         there (inline initialisers don't run behind a proxy), so it is 0 and rejects any non-zero fee.
     */
    function setTemplateConfig(
        ContractType _contractType,
        uint256 _platformFeePercent,
        uint256 _minRecipients,
        uint256 _maxRecipients
    ) external onlyRole(TEMPLATE_MANAGER_ROLE) {
        require(_platformFeePercent <= MAX_TEMPLATE_PLATFORM_FEE, "Platform fee too high");
        require(_minRecipients > 0 && _maxRecipients >= _minRecipients, "Invalid recipient limits");
        ContractTemplate storage template = templates[_contractType];
        template.platformFeePercent = _platformFeePercent;
        template.minRecipients = _minRecipients;
        template.maxRecipients = _maxRecipients;
        emit TemplateUpdated(_contractType, template.active);
    }

    /**
     * @notice Add or update contract template
     */
    function addTemplate(
        ContractType _contractType,
        string memory _name,
        string memory _description,
        uint256 _platformFeePercent,
        uint256 _minRecipients,
        uint256 _maxRecipients,
        address _implementationAddress
    ) external onlyRole(TEMPLATE_MANAGER_ROLE) {
        require(_platformFeePercent <= maxPlatformFee, "Platform fee too high");
        require(_minRecipients > 0, "Min recipients must be > 0");
        require(_maxRecipients >= _minRecipients, "Max recipients must be >= min");
        require(_implementationAddress != address(0), "Invalid implementation address");
        require(_implementationAddress.code.length > 0, "Implementation must be a contract");

        templates[_contractType] = ContractTemplate({
            name: _name,
            description: _description,
            platformFeePercent: _platformFeePercent,
            minRecipients: _minRecipients,
            maxRecipients: _maxRecipients,
            active: true,
            implementationAddress: _implementationAddress
        });

        emit TemplateAdded(_contractType, _name, _implementationAddress);
    }

    /**
     * @notice Toggle template active status
     */
    function toggleTemplate(ContractType _contractType) external onlyRole(TEMPLATE_MANAGER_ROLE) {
        templates[_contractType].active = !templates[_contractType].active;
        emit TemplateUpdated(_contractType, templates[_contractType].active);
    }

    /**
     * @notice Update platform treasury
     */
    function setPlatformTreasury(address _newTreasury) external onlyRole(ADMIN_ROLE) {
        require(_newTreasury != address(0), "Invalid treasury address");
        address oldTreasury = platformTreasury;
        platformTreasury = _newTreasury;
        emit PlatformTreasuryUpdated(oldTreasury, _newTreasury);
    }

    /**
     * @notice Update default platform fee
     */
    function setDefaultPlatformFee(uint256 _newFee) external onlyRole(ADMIN_ROLE) {
        require(_newFee <= maxPlatformFee, "Fee too high");
        uint256 oldFee = defaultPlatformFee;
        defaultPlatformFee = _newFee;
        emit PlatformFeeUpdated(oldFee, _newFee);
    }

    /**
     * @notice Set contract creation fee to $10 USD equivalent
     * @dev For USDT/USDC (6 decimals): 10 * 10^6 = 10_000_000
     *      For DAI (18 decimals): 10 * 10^18 = 10_000_000_000_000_000_000
     * @param _fee Fee amount in token units (e.g., 10_000_000 for 10 USDT)
     */
    function setContractCreationFee(uint256 _fee) external onlyRole(ADMIN_ROLE) {
        uint256 oldFee = contractCreationFee;
        contractCreationFee = _fee;
        emit CreationFeeUpdated(oldFee, _fee);
    }

    /**
     * @notice Toggle creation fee on/off
     */
    function toggleCreationFee(bool _enabled) external onlyRole(ADMIN_ROLE) {
        creationFeeEnabled = _enabled;
    }

    /**
     * @notice Set MembershipManager contract address
     */
    function setMembershipManager(address _membershipManager) external onlyRole(ADMIN_ROLE) {
        address oldManager = address(membershipManager);
        membershipManager = MembershipManager(_membershipManager);
        emit MembershipManagerUpdated(oldManager, _membershipManager);
    }

    /**
     * @notice Toggle membership requirement on/off
     */
    function setMembershipRequired(bool _required) external onlyRole(ADMIN_ROLE) {
        membershipRequired = _required;
        emit MembershipRequirementUpdated(_required);
    }

    /**
     * @notice Set escrow admin address for dispute resolution
     */
    function setEscrowAdmin(address _newAdmin) external onlyRole(ADMIN_ROLE) {
        require(_newAdmin != address(0), "Invalid admin address");
        address oldAdmin = escrowAdmin;
        escrowAdmin = _newAdmin;
        emit EscrowAdminUpdated(oldAdmin, _newAdmin);
    }

    /**
     * @notice Get creation fee information
     * @return enabled Whether creation fee is enabled
     * @return fee Fee amount in token units
     */
    function getCreationFeeInfo() external view returns (bool enabled, uint256 fee) {
        return (creationFeeEnabled, contractCreationFee);
    }

    /**
     * @notice Get all payment contracts
     */
    function getAllPaymentContracts() external view returns (address[] memory) {
        return allPaymentContracts;
    }

    /**
     * @notice Get contracts created by user (O(1) operation)
     */
    function getUserContracts(address _user) external view returns (address[] memory) {
        return contractsByUser[_user];
    }

    /**
     * @notice Get template information
     */
    function getTemplate(ContractType _contractType) external view returns (ContractTemplate memory) {
        return templates[_contractType];
    }

    /**
     * @notice Pause contract (admin only)
     */
    function pause() external onlyRole(ADMIN_ROLE) {
        _pause();
    }

    /**
     * Unpause contract (admin only)
     */
    function unpause() external onlyRole(ADMIN_ROLE) {
        _unpause();
    }

    /**
     * @notice Authorize upgrade (UUPS pattern)
     * @dev Only DEFAULT_ADMIN_ROLE can upgrade the contract
     * @param newImplementation Address of new implementation contract
     */
    function _authorizeUpgrade(address newImplementation) 
        internal 
        override 
        onlyRole(DEFAULT_ADMIN_ROLE) 
    {
        require(newImplementation != address(0), "Invalid implementation address");
    }

    uint256[50] private __gap;
}

contracts/payment-factory/MembershipManager.sol

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

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/**
 * @title MembershipManager
 * @notice Manages platform-wide subscription system for all participants
 * @dev Lifecycle: ACTIVE → REFUNDED → PAUSED (during payments) → ACTIVE (fresh period)
 * 
 * Key Features:
 * - Monthly $10 USDC subscription via allowance-based collection
 * - First 6 months ($60) reserved as refundable buffer
 * - Months 7+: Direct income to Treasury
 * - Auto-refund when participant's contract ≥$2000 receives payment
 * - Auto-pause while contract has active payments
 * - Auto-resume with fresh 6-month period when payments cease
 */
contract MembershipManager is 
    AccessControl,
    ReentrancyGuard,
    Pausable
{
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
    bytes32 public constant PAYMENT_FACTORY_ROLE = keccak256("PAYMENT_FACTORY_ROLE");
    bytes32 public constant TREASURY_ROLE = keccak256("TREASURY_ROLE");

    uint256 public monthlyFee; // Monthly subscription fee (configurable, default $10)
    uint256 public constant REFUND_BUFFER_MONTHS = 6;
    uint256 public refundThreshold; // Contract value threshold for triggering refund (default $2000)
    uint256 public paymentPeriod; // Duration between payments (default 30 days)
    uint256 public constant MAX_MISSED_PAYMENTS = 3; // Block access after 3 missed collection attempts
    uint256 public constant RETRY_DELAY = 1 days; // Wait 1 day between failed collection attempts

    enum SubscriptionStatus {
        INACTIVE,    // Never subscribed or cancelled
        ACTIVE,      // Collecting monthly payments
        PAUSED       // Temporarily paused during active contract payments
    }

    struct Subscription {
        SubscriptionStatus status;
        uint256 totalPaid;              // Total amount paid over lifetime
        uint256 reservedAmount;         // Current reserve buffer (max $60)
        uint256 currentPeriodStart;     // When current subscription period started
        uint256 lastPaymentTime;        // Last successful payment collection
        uint256 pausedAt;               // When subscription was paused (0 if not paused)
        bool hasReceivedRefund;         // True if refund was issued in current period
        address[] activeContracts;      // Contracts with active payments
        uint256 missedPayments;         // Counter for failed payment attempts
        uint256 lastFailedAttempt;      // Timestamp of last failed collection
    }

    IERC20 public usdc;
    address public treasury;
    mapping(address => Subscription) public subscriptions;
    mapping(address => mapping(address => bool)) public contractTracking; // participant => contract => isActive
    address[] public allSubscribers; // Array to track all subscribers
    mapping(address => bool) private subscriberExists; // Quick lookup for existence

    // Events
    event SubscriptionStarted(address indexed participant, uint256 timestamp);
    event PaymentCollected(address indexed participant, uint256 amount, uint256 monthsPaid);
    event PaymentFailed(address indexed participant, uint256 missedCount, uint256 timestamp);
    event AccessBlocked(address indexed participant, uint256 missedPayments);
    event SubscriptionStopped(address indexed participant, uint256 reserve);
    event RefundIssued(address indexed participant, uint256 amount, address indexed triggeringContract);
    event SubscriptionPaused(address indexed participant, address indexed contractAddress, uint256 timestamp);
    event SubscriptionResumed(address indexed participant, uint256 newPeriodStart);
    event SubscriptionCancelled(address indexed participant);
    event PaymentPeriodUpdated(uint256 oldPeriod, uint256 newPeriod);
    event MonthlyFeeUpdated(uint256 oldFee, uint256 newFee);
    event RefundThresholdUpdated(uint256 oldThreshold, uint256 newThreshold);

    constructor(
        address _usdc,
        address _treasury,
        address _admin
    ) {
        require(_usdc != address(0), "Invalid USDC address");
        require(_treasury != address(0), "Invalid treasury address");
        require(_admin != address(0), "Invalid admin address");

        usdc = IERC20(_usdc);
        treasury = _treasury;
        monthlyFee = 10e6; // Default $10 USDC
        paymentPeriod = 30 days; // Default to 30 days
        refundThreshold = 2000e6; // Default $2000 USDC

        _grantRole(DEFAULT_ADMIN_ROLE, _admin);
        _grantRole(ADMIN_ROLE, _admin);
        _grantRole(TREASURY_ROLE, _treasury);
    }

    /**
     * @notice Start subscription for a participant
     * @dev Participant must first approve USDC allowance for this contract
     * @dev First payment is collected immediately upon subscription
     */
    function subscribe() external nonReentrant whenNotPaused {
        Subscription storage sub = subscriptions[msg.sender];
        require(sub.status == SubscriptionStatus.INACTIVE, "Already subscribed");

        // Collect first payment immediately
        require(
            usdc.transferFrom(msg.sender, address(this), monthlyFee),
            "First payment failed - insufficient allowance or balance"
        );

        sub.status = SubscriptionStatus.ACTIVE;
        sub.currentPeriodStart = block.timestamp;
        sub.reservedAmount = monthlyFee; // First payment goes to reserve
        sub.totalPaid = monthlyFee;
        sub.hasReceivedRefund = false;
        sub.lastPaymentTime = block.timestamp; // Mark first payment time
        sub.missedPayments = 0;

        // Add to subscribers array if first time
        if (!subscriberExists[msg.sender]) {
            allSubscribers.push(msg.sender);
            subscriberExists[msg.sender] = true;
        }

        emit SubscriptionStarted(msg.sender, block.timestamp);
        emit PaymentCollected(msg.sender, monthlyFee, 1); // 1 month paid
    }

    /**
     * @notice Collect monthly payment from participant
     * @dev Called by Treasury periodically (e.g., via automation)
     * @dev If payment fails repeatedly, subscription is stopped after MAX_MISSED_PAYMENTS
     * @param participant Address to collect payment from
     */
    function collectPayment(address participant) 
        external 
        nonReentrant 
        whenNotPaused 
        onlyRole(TREASURY_ROLE) 
    {
        Subscription storage sub = subscriptions[participant];
        require(sub.status == SubscriptionStatus.ACTIVE, "Subscription not active");
        
        // Check if enough time has passed since last payment
        require(
            block.timestamp >= sub.lastPaymentTime + paymentPeriod,
            "Payment too soon - period not elapsed"
        );

        // If there was a previous failed attempt, check retry delay
        if (sub.lastFailedAttempt > 0) {
            require(
                block.timestamp >= sub.lastFailedAttempt + RETRY_DELAY,
                "Too soon - wait 1 day between retry attempts"
            );
        }

        // Try to transfer USDC from participant to this contract
        bool success;
        try usdc.transferFrom(participant, address(this), monthlyFee) returns (bool result) {
            success = result;
        } catch {
            success = false;
        }
        
        if (!success) {
            // Payment failed - increment missed payments counter
            sub.missedPayments++;
            sub.lastFailedAttempt = block.timestamp;
            
            emit PaymentFailed(participant, sub.missedPayments, block.timestamp);
            
            // Stop subscription after max missed attempts to avoid multi-month backpay
            if (sub.missedPayments >= MAX_MISSED_PAYMENTS) {
                _stopSubscription(participant);
                emit AccessBlocked(participant, MAX_MISSED_PAYMENTS);
            }
            
            return;
        }

        // Payment successful - reset missed payments counter
        sub.missedPayments = 0;
        sub.lastFailedAttempt = 0;
        sub.totalPaid += monthlyFee;
        sub.lastPaymentTime = block.timestamp;

        // First 6 months go to reserved buffer
        uint256 monthsPaid = sub.totalPaid / monthlyFee;
        if (monthsPaid <= REFUND_BUFFER_MONTHS) {
            sub.reservedAmount += monthlyFee;
            // Keep funds in contract as reserve
        } else {
            // After 6 months, transfer directly to Treasury
            require(
                usdc.transfer(treasury, monthlyFee),
                "Treasury transfer failed"
            );
        }

        emit PaymentCollected(participant, monthlyFee, monthsPaid);
    }

    /**
     * @notice Collect monthly payments from multiple participants in one transaction
     * @dev Batch version of collectPayment - saves gas for admin
     * @dev Continues on failure - does not revert if one participant fails
     * @param participants Array of addresses to collect payments from
     * @return successCount Number of successful collections
     * @return failedAddresses Array of addresses that failed
     */
    function collectPaymentBatch(address[] calldata participants) 
        external 
        nonReentrant 
        whenNotPaused 
        onlyRole(TREASURY_ROLE)
        returns (uint256 successCount, address[] memory failedAddresses)
    {
        require(participants.length > 0, "Empty participants array");
        require(participants.length <= 50, "Too many participants (max 50)");
        
        address[] memory failed = new address[](participants.length);
        uint256 failedCount = 0;
        
        for (uint256 i = 0; i < participants.length; i++) {
            address participant = participants[i];
            Subscription storage sub = subscriptions[participant];
            
            // Skip if not active
            if (sub.status != SubscriptionStatus.ACTIVE) {
                failed[failedCount] = participant;
                failedCount++;
                continue;
            }
            
            // Skip if payment period not elapsed
            if (block.timestamp < sub.lastPaymentTime + paymentPeriod) {
                failed[failedCount] = participant;
                failedCount++;
                continue;
            }

            // Skip if retry delay not elapsed (wait 1 day between failed attempts)
            if (sub.lastFailedAttempt > 0 && block.timestamp < sub.lastFailedAttempt + RETRY_DELAY) {
                failed[failedCount] = participant;
                failedCount++;
                continue;
            }
            
            // Try to collect payment (using transferFrom)
            bool success;
            try usdc.transferFrom(participant, address(this), monthlyFee) returns (bool result) {
                success = result;
            } catch {
                success = false;
            }
            
            if (!success) {
                // Payment failed - increment missed payments counter
                sub.missedPayments++;
                sub.lastFailedAttempt = block.timestamp;
                
                emit PaymentFailed(participant, sub.missedPayments, block.timestamp);
                
                // Stop subscription after max missed attempts
                if (sub.missedPayments >= MAX_MISSED_PAYMENTS) {
                    _stopSubscription(participant);
                    emit AccessBlocked(participant, MAX_MISSED_PAYMENTS);
                }
                
                failed[failedCount] = participant;
                failedCount++;
                continue;
            }
            
            // Payment successful - reset missed payments counter
            sub.missedPayments = 0;
            sub.lastFailedAttempt = 0;
            sub.totalPaid += monthlyFee;
            sub.lastPaymentTime = block.timestamp;
            
            // First 6 months go to reserved buffer
            uint256 monthsPaid = sub.totalPaid / monthlyFee;
            if (monthsPaid <= REFUND_BUFFER_MONTHS) {
                sub.reservedAmount += monthlyFee;
            } else {
                // After 6 months, transfer directly to Treasury
                // Note: We don't revert here if treasury transfer fails
                // to avoid breaking the entire batch
                usdc.transfer(treasury, monthlyFee);
            }
            
            emit PaymentCollected(participant, monthlyFee, monthsPaid);
            successCount++;
        }
        
        // Resize failed array to actual size
        failedAddresses = new address[](failedCount);
        for (uint256 i = 0; i < failedCount; i++) {
            failedAddresses[i] = failed[i];
        }
        
        return (successCount, failedAddresses);
    }

    /**
     * @notice Process refund for participants when contract ≥$2000 receives payment
     * @dev Called by PaymentFactory when first payment is made on qualifying contract
     * @param participants All participants involved in the contract (HR, Dev, Partner, Client)
     * @param contractAddress The contract that triggered the refund
     */
    function processRefund(
        address[] calldata participants,
        address contractAddress
    ) external nonReentrant onlyRole(PAYMENT_FACTORY_ROLE) {
        for (uint256 i = 0; i < participants.length; i++) {
            address participant = participants[i];
            Subscription storage sub = subscriptions[participant];

            // Only process if active subscription and hasn't received refund in this period
            if (sub.status != SubscriptionStatus.ACTIVE || sub.hasReceivedRefund) {
                continue;
            }

            uint256 refundAmount = sub.reservedAmount > 0 ? sub.reservedAmount : 0;
            
            if (refundAmount > 0) {
                // Transfer refund to participant
                require(
                    usdc.transfer(participant, refundAmount),
                    "Refund transfer failed"
                );

                sub.hasReceivedRefund = true;
                sub.reservedAmount = 0; // Clear reserved amount after refund

                emit RefundIssued(participant, refundAmount, contractAddress);
            }
        }
    }

    /**
     * @notice Pause subscription when participant's contract starts receiving payments
     * @dev Called by PaymentFactory when payments begin on contract ≥$2000
     * @param participant Participant whose subscription to pause
     * @param contractAddress The contract triggering the pause
     */
    function pauseSubscription(
        address participant,
        address contractAddress
    ) external nonReentrant onlyRole(PAYMENT_FACTORY_ROLE) {
        Subscription storage sub = subscriptions[participant];
        
        // Only pause if currently active
        if (sub.status != SubscriptionStatus.ACTIVE) {
            return;
        }

        // Add contract to active list if not already tracked
        if (!contractTracking[participant][contractAddress]) {
            sub.activeContracts.push(contractAddress);
            contractTracking[participant][contractAddress] = true;
        }

        sub.status = SubscriptionStatus.PAUSED;
        sub.pausedAt = block.timestamp;

        emit SubscriptionPaused(participant, contractAddress, block.timestamp);
    }

    /**
     * @notice Resume subscription when payments cease on participant's contract
     * @dev Called by PaymentFactory when contract payments stop
     * @param participant Participant whose subscription to resume
     * @param contractAddress The contract that stopped payments
     */
    function resumeSubscription(
        address participant,
        address contractAddress
    ) external nonReentrant onlyRole(PAYMENT_FACTORY_ROLE) {
        Subscription storage sub = subscriptions[participant];
        
        if (sub.status != SubscriptionStatus.PAUSED) {
            return;
        }

        // Remove contract from active list
        if (contractTracking[participant][contractAddress]) {
            _removeActiveContract(participant, contractAddress);
            contractTracking[participant][contractAddress] = false;
        }

        // Only resume if no more active contracts
        if (sub.activeContracts.length == 0) {
            sub.status = SubscriptionStatus.ACTIVE;
            
            // START FRESH PERIOD with new 6-month reserve cycle
            sub.currentPeriodStart = block.timestamp;
            sub.reservedAmount = 0; // Reset reserve for new period
            sub.hasReceivedRefund = false; // Can receive refund again in new period
            sub.pausedAt = 0;
            sub.lastPaymentTime = 0; // Reset to allow immediate first payment in new period

            emit SubscriptionResumed(participant, block.timestamp);
        }
    }


    /**
     * @notice Cancel subscription
     * @dev Participant can cancel at any time, forfeits reserved amount
     */
    function cancelSubscription() external nonReentrant {
        Subscription storage sub = subscriptions[msg.sender];
        require(sub.status != SubscriptionStatus.INACTIVE, "No active subscription");

        // Transfer any remaining reserved amount to Treasury (no refund on cancellation)
        if (sub.reservedAmount > 0) {
            require(
                usdc.transfer(treasury, sub.reservedAmount),
                "Treasury transfer failed"
            );
        }

        // Clear all data
        delete subscriptions[msg.sender];
        
        emit SubscriptionCancelled(msg.sender);
    }

    /**
     * @notice Internal: stop subscription after repeated failed payments
     * @dev Forfeits reserved buffer to treasury and clears subscription record
     */
    function _stopSubscription(address participant) internal {
        Subscription storage sub = subscriptions[participant];

        uint256 reserved = sub.reservedAmount;
        if (reserved > 0) {
            usdc.transfer(treasury, reserved);
        }

        delete subscriptions[participant];

        emit SubscriptionStopped(participant, reserved);
    }

    /**
     * @notice Remove contract from active contracts array
     * @dev Internal helper function
     */
    function _removeActiveContract(address participant, address contractAddress) private {
        Subscription storage sub = subscriptions[participant];
        
        for (uint256 i = 0; i < sub.activeContracts.length; i++) {
            if (sub.activeContracts[i] == contractAddress) {
                // Move last element to this position and pop
                sub.activeContracts[i] = sub.activeContracts[sub.activeContracts.length - 1];
                sub.activeContracts.pop();
                break;
            }
        }
    }

    // ==================== VIEW FUNCTIONS ====================

    /**
     * @notice Get subscription details for participant
     */
    function getSubscription(address participant) 
        external 
        view 
        returns (
            SubscriptionStatus status,
            uint256 totalPaid,
            uint256 reservedAmount,
            uint256 currentPeriodStart,
            uint256 lastPaymentTime,
            bool hasReceivedRefund,
            uint256 activeContractsCount
        ) 
    {
        Subscription storage sub = subscriptions[participant];
        return (
            sub.status,
            sub.totalPaid,
            sub.reservedAmount,
            sub.currentPeriodStart,
            sub.lastPaymentTime,
            sub.hasReceivedRefund,
            sub.activeContracts.length
        );
    }

    /**
     * @notice Check if participant has active subscription (not blocked)
     * @dev Use this in PaymentFactory to restrict access to platform
     */
    function hasActiveSubscription(address participant) external view returns (bool) {
        SubscriptionStatus status = subscriptions[participant].status;
        return status == SubscriptionStatus.ACTIVE || status == SubscriptionStatus.PAUSED;
    }

    /**
     * @notice Get missed payments count
     */
    function getMissedPayments(address participant) external view returns (uint256) {
        return subscriptions[participant].missedPayments;
    }

    /**
     * @notice Calculate how many payment periods have been missed (not yet attempted to collect)
     * @dev This shows the real number of periods that passed without payment
     * @return periodsCount Number of full payment periods missed
     * @return amountDue Total amount due for all missed periods
     */
    function getMissedPeriodsCount(address participant) 
        external 
        view 
        returns (uint256 periodsCount, uint256 amountDue) 
    {
        Subscription storage sub = subscriptions[participant];
        
        // Only calculate for active subscriptions
        if (sub.status != SubscriptionStatus.ACTIVE) {
            return (0, 0);
        }
        
        // No periods missed if not subscribed or payment period not set
        if (sub.currentPeriodStart == 0 || paymentPeriod == 0) {
            return (0, 0);
        }
        
        uint256 timeSinceLastPayment;
        if (sub.lastPaymentTime == 0) {
            // First payment - check time since subscription start
            timeSinceLastPayment = block.timestamp - sub.currentPeriodStart;
        } else {
            // Check time since last successful payment
            timeSinceLastPayment = block.timestamp - sub.lastPaymentTime;
        }
        
        // Calculate number of full periods missed
        if (timeSinceLastPayment >= paymentPeriod) {
            periodsCount = timeSinceLastPayment / paymentPeriod;
            amountDue = periodsCount * monthlyFee;
        } else {
            periodsCount = 0;
            amountDue = 0;
        }
        
        return (periodsCount, amountDue);
    }

    /**
     * @notice Check if participant can receive payment collection
     */
    function canCollectPayment(address participant) external view returns (bool) {
        Subscription storage sub = subscriptions[participant];
        
        if (sub.status != SubscriptionStatus.ACTIVE) {
            return false;
        }
        
        if (sub.lastPaymentTime == 0) {
            return true; // First payment
        }
        
        return block.timestamp >= sub.lastPaymentTime + paymentPeriod;
    }

    /**
     * @notice Get total number of subscribers
     */
    function getSubscribersCount() external view returns (uint256) {
        return allSubscribers.length;
    }

    /**
     * @notice Get paginated list of subscribers
     * @param offset Starting index
     * @param limit Maximum number to return
     */
    function getSubscribers(uint256 offset, uint256 limit) 
        external 
        view 
        returns (address[] memory) 
    {
        uint256 total = allSubscribers.length;
        if (offset >= total) {
            return new address[](0);
        }

        uint256 end = offset + limit;
        if (end > total) {
            end = total;
        }

        uint256 resultLength = end - offset;
        address[] memory result = new address[](resultLength);
        
        for (uint256 i = 0; i < resultLength; i++) {
            result[i] = allSubscribers[offset + i];
        }

        return result;
    }

    /**
     * @notice Get all active contracts for participant
     */
    function getActiveContracts(address participant) external view returns (address[] memory) {
        return subscriptions[participant].activeContracts;
    }

    // ==================== ADMIN FUNCTIONS ====================

    /**
     * @notice Update treasury address
     */
    function setTreasury(address _treasury) external onlyRole(ADMIN_ROLE) {
        require(_treasury != address(0), "Invalid treasury address");
        treasury = _treasury;
        _grantRole(TREASURY_ROLE, _treasury);
    }

    /**
     * @notice Grant PaymentFactory role to factory contract
     */
    function setPaymentFactory(address _factory) external onlyRole(ADMIN_ROLE) {
        require(_factory != address(0), "Invalid factory address");
        _grantRole(PAYMENT_FACTORY_ROLE, _factory);
    }

    /**
     * @notice Emergency pause
     */
    function pause() external onlyRole(ADMIN_ROLE) {
        _pause();
    }

    /**
     * @notice Unpause
     */
    function unpause() external onlyRole(ADMIN_ROLE) {
        _unpause();
    }

    /**
     * @notice Update payment period
     * @param newPeriod New duration between payments in seconds
     */
    function setPaymentPeriod(uint256 newPeriod) external onlyRole(ADMIN_ROLE) {
        require(newPeriod >= 3 minutes, "Period too short (min 3 minutes)");
        require(newPeriod <= 365 days, "Period too long");
        
        uint256 oldPeriod = paymentPeriod;
        paymentPeriod = newPeriod;
        
        emit PaymentPeriodUpdated(oldPeriod, newPeriod);
    }

    /**
     * @notice Update monthly subscription fee
     * @param newFee New monthly fee in USDC (6 decimals)
     */
    function setMonthlyFee(uint256 newFee) external onlyRole(ADMIN_ROLE) {
        require(newFee >= 0.1e6, "Fee too low (min $0.10)");
        require(newFee <= 100e6, "Fee too high (max $100)");
        
        uint256 oldFee = monthlyFee;
        monthlyFee = newFee;
        
        emit MonthlyFeeUpdated(oldFee, newFee);
    }

    /**
     * @notice Update refund threshold
     * @param newThreshold New contract value threshold in USDC (6 decimals)
     */
    function setRefundThreshold(uint256 newThreshold) external onlyRole(ADMIN_ROLE) {
        require(newThreshold >= 2e6, "Threshold too low (min $2)");
        require(newThreshold <= 100000e6, "Threshold too high (max $100k)");
        
        uint256 oldThreshold = refundThreshold;
        refundThreshold = newThreshold;
        
        emit RefundThresholdUpdated(oldThreshold, newThreshold);
    }

    /**
     * @notice Get contract version
     */
    function version() external pure returns (string memory) {
        return "1.0.0";
    }
}

contracts/payment-factory/TreasuryManager.sol

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

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IAavePool.sol";

/**
 * @title TreasuryManager
 * @notice Central treasury contract that manages all platform funds and integrates with Aave V3
 * @dev Handles:
 *      - Creation fees from PaymentFactory
 *      - Platform fees from payment contracts (2%)
 *      - Reputation Vault deposits
 *      - Aave V3 staking on Arbitrum for yield generation
 *      - Future: Bridge to Mainnet for Aave Umbrella (higher APY)
 */
contract TreasuryManager is AccessControl, ReentrancyGuard, Pausable {
    using SafeERC20 for IERC20;

    bytes32 public constant TREASURY_ADMIN = keccak256("TREASURY_ADMIN");
    bytes32 public constant FEE_COLLECTOR = keccak256("FEE_COLLECTOR");

    // DAO Treasury address - receives funds transferred from this contract
    address public immutable daoTreasury;

    // Minimum reserve to keep available (not staked) for operational expenses
    uint256 public minAvailableReserve; // Configurable reserve amount

    // Aave V3 Pool on Arbitrum
    IAavePool public immutable aavePool;
    
    // Primary stablecoin (USDC on Arbitrum)
    IERC20 public immutable stablecoin;
    
    // aToken received from Aave (aArbUSDC)
    IERC20 public immutable aToken;

    // Tracking
    uint256 public totalDeposited;      // Total ever deposited
    uint256 public totalWithdrawn;      // Total ever withdrawn
    uint256 public totalStakedInAave;   // Currently staked in Aave
    uint256 public totalYieldClaimed;   // Lifetime yield claimed

    // Source tracking for transparency
    mapping(address => uint256) public depositsBySource;  // Track deposits by contract
    mapping(address => uint256) public withdrawalsBySource;

    // Events
    event FundsReceived(address indexed from, uint256 amount, string source);
    event StakedInAave(uint256 amount, uint256 timestamp);
    event WithdrawnFromAave(uint256 amount, uint256 timestamp);
    event YieldClaimed(uint256 amount, address indexed recipient);
    event EmergencyWithdrawal(address indexed token, uint256 amount, address indexed recipient);
    event AaveBalanceSnapshot(uint256 aTokenBalance, uint256 underlyingBalance, uint256 yieldGenerated);
    event MinReserveUpdated(uint256 oldReserve, uint256 newReserve);
    event TransferredToDAO(uint256 amount, address indexed daoTreasury);

    /**
     * @notice Constructor
     * @param _aavePool Address of Aave V3 Pool on Arbitrum (0x794a61358D6845594F94dc1DB02A252b5b4814aD)
     * @param _stablecoin Address of USDC on Arbitrum
     * @param _aToken Address of aArbUSDC token
     * @param _admin Treasury admin address
     * @param _daoTreasury Address of DAO Treasury (receives transferred funds)
     * @param _minReserve Minimum reserve to keep available (e.g., 100e6 for $100 USDC)
     */
    constructor(
        address _aavePool,
        address _stablecoin,
        address _aToken,
        address _admin,
        address _daoTreasury,
        uint256 _minReserve
    ) {
        require(_aavePool != address(0), "Invalid Aave pool");
        require(_stablecoin != address(0), "Invalid stablecoin");
        require(_aToken != address(0), "Invalid aToken");
        require(_admin != address(0), "Invalid admin");
        require(_daoTreasury != address(0), "Invalid DAO treasury");

        aavePool = IAavePool(_aavePool);
        stablecoin = IERC20(_stablecoin);
        aToken = IERC20(_aToken);
        daoTreasury = _daoTreasury;
        minAvailableReserve = _minReserve;

        _grantRole(DEFAULT_ADMIN_ROLE, _admin);
        _grantRole(TREASURY_ADMIN, _admin);
    }

    /**
     * @notice Receive funds from payment contracts or other sources
     * @param amount Amount of stablecoin to deposit
     * @param source Description of fund source (e.g., "creation_fee", "platform_fee", "reputation_vault")
     */
    function receiveFunds(uint256 amount, string calldata source) 
        external 
        whenNotPaused 
        nonReentrant 
    {
        require(amount > 0, "Amount must be > 0");
        
        stablecoin.safeTransferFrom(msg.sender, address(this), amount);
        
        totalDeposited += amount;
        depositsBySource[msg.sender] += amount;
        
        emit FundsReceived(msg.sender, amount, source);
    }

    /**
     * @notice Stake funds in Aave V3 to earn yield
     * @param amount Amount to stake (0 = stake all available balance minus reserve)
     */
    function stakeInAave(uint256 amount) 
        external 
        onlyRole(TREASURY_ADMIN) 
        whenNotPaused 
        nonReentrant 
    {
        uint256 availableBalance = stablecoin.balanceOf(address(this));
        require(availableBalance > minAvailableReserve, "Insufficient balance after reserve");
        
        uint256 maxStakeable = availableBalance - minAvailableReserve;
        uint256 stakeAmount = amount == 0 ? maxStakeable : amount;
        require(stakeAmount <= maxStakeable, "Would leave insufficient reserve");
        
        // Approve Aave pool
        stablecoin.safeApprove(address(aavePool), stakeAmount);
        
        // Supply to Aave (referral code 0)
        aavePool.supply(address(stablecoin), stakeAmount, address(this), 0);
        
        totalStakedInAave += stakeAmount;
        
        emit StakedInAave(stakeAmount, block.timestamp);
    }

    /**
     * @notice Withdraw funds from Aave V3 back to this contract
     * @param amount Amount to withdraw (type(uint256).max = withdraw all)
     * @dev Funds are withdrawn to address(this), not to an arbitrary recipient
     */
    function withdrawFromAave(uint256 amount) 
        external 
        onlyRole(TREASURY_ADMIN) 
        nonReentrant 
        returns (uint256) 
    {
        // Withdraw from Aave to this contract
        uint256 withdrawn = aavePool.withdraw(address(stablecoin), amount, address(this));
        
        totalWithdrawn += withdrawn;
        
        if (amount == type(uint256).max) {
            totalStakedInAave = 0;
        } else {
            totalStakedInAave -= withdrawn;
        }
        
        emit WithdrawnFromAave(withdrawn, block.timestamp);
        
        return withdrawn;
    }

    /**
     * @notice Claim yield generated from Aave staking back to this contract
     * @dev Yield = aToken balance - totalStakedInAave
     */
    function claimYield() 
        external 
        onlyRole(TREASURY_ADMIN) 
        nonReentrant 
        returns (uint256) 
    {
        uint256 aTokenBalance = aToken.balanceOf(address(this));
        require(aTokenBalance > totalStakedInAave, "No yield to claim");
        
        uint256 yieldAmount = aTokenBalance - totalStakedInAave;
        
        // Withdraw only the yield to this contract
        uint256 withdrawn = aavePool.withdraw(address(stablecoin), yieldAmount, address(this));
        
        totalYieldClaimed += withdrawn;
        
        emit YieldClaimed(withdrawn, address(this));
        
        return withdrawn;
    }

    /**
     * @notice Transfer funds from this contract to DAO Treasury
     * @param amount Amount of USDC to transfer
     * @dev Admin can transfer available balance (not staked) to DAO Treasury
     */
    function transferToDAO(uint256 amount) 
        external 
        onlyRole(TREASURY_ADMIN) 
        nonReentrant 
    {
        uint256 availableBalance = stablecoin.balanceOf(address(this));
        require(amount <= availableBalance, "Insufficient available balance");
        require(amount > 0, "Amount must be greater than 0");
        
        stablecoin.safeTransfer(daoTreasury, amount);
        
        emit TransferredToDAO(amount, daoTreasury);
    }

    /**
     * @notice Get current Aave balance and generated yield
     * @return aTokenBalance Current aToken balance
     * @return underlyingValue Underlying USDC value
     * @return yieldGenerated Yield generated (aToken balance - staked amount)
     */
    function getAaveBalance() 
        external 
        view 
        returns (
            uint256 aTokenBalance,
            uint256 underlyingValue,
            uint256 yieldGenerated
        ) 
    {
        aTokenBalance = aToken.balanceOf(address(this));
        underlyingValue = aTokenBalance; // aToken is 1:1 with underlying
        yieldGenerated = aTokenBalance > totalStakedInAave ? aTokenBalance - totalStakedInAave : 0;
    }

    /**
     * @notice Take a snapshot of current Aave balance and yield
     * @dev Emits event for off-chain tracking
     */
    function snapshotAaveBalance() 
        external 
        onlyRole(TREASURY_ADMIN) 
    {
        uint256 aTokenBalance = aToken.balanceOf(address(this));
        uint256 yieldGenerated = aTokenBalance > totalStakedInAave ? aTokenBalance - totalStakedInAave : 0;
        
        emit AaveBalanceSnapshot(aTokenBalance, aTokenBalance, yieldGenerated);
    }

    /**
     * @notice Get available balance not yet staked in Aave
     */
    function getAvailableBalance() external view returns (uint256) {
        return stablecoin.balanceOf(address(this));
    }

    /**
     * @notice Get total treasury value (available + staked)
     */
    function getTotalValue() external view returns (uint256) {
        uint256 available = stablecoin.balanceOf(address(this));
        uint256 aTokenBalance = aToken.balanceOf(address(this));
        return available + aTokenBalance;
    }

    /**
     * @notice Grant FEE_COLLECTOR role to payment contracts
     * @param collector Address to grant role to (PaymentFactory, SimpleHRDevContract, etc.)
     */
    function addFeeCollector(address collector) 
        external 
        onlyRole(DEFAULT_ADMIN_ROLE) 
    {
        grantRole(FEE_COLLECTOR, collector);
    }

    /**
     * @notice Revoke FEE_COLLECTOR role
     */
    function removeFeeCollector(address collector) 
        external 
        onlyRole(DEFAULT_ADMIN_ROLE) 
    {
        revokeRole(FEE_COLLECTOR, collector);
    }

    /**
     * @notice Pause contract (emergency)
     */
    function pause() external onlyRole(TREASURY_ADMIN) {
        _pause();
    }

    /**
     * @notice Update minimum available reserve
     * @param newReserve New minimum reserve amount
     */
    function setMinAvailableReserve(uint256 newReserve) external onlyRole(TREASURY_ADMIN) {
        uint256 oldReserve = minAvailableReserve;
        minAvailableReserve = newReserve;
        emit MinReserveUpdated(oldReserve, newReserve);
    }

    /**
     * @notice Unpause contract
     */
    function unpause() external onlyRole(TREASURY_ADMIN) {
        _unpause();
    }

    /**
     * @notice Emergency withdrawal (only if Aave fails or other critical issue)
     * @param token Token to withdraw
     * @param amount Amount to withdraw
     * @param recipient Recipient address
     */
    function emergencyWithdraw(
        address token,
        uint256 amount,
        address recipient
    ) 
        external 
        onlyRole(DEFAULT_ADMIN_ROLE) 
    {
        require(recipient != address(0), "Invalid recipient");
        IERC20(token).safeTransfer(recipient, amount);
        emit EmergencyWithdrawal(token, amount, recipient);
    }

    // Future: Bridge to Mainnet functionality
    // function bridgeToMainnet(uint256 amount) external onlyRole(TREASURY_ADMIN) { }
    // function stakeInMainnetUmbrella(uint256 amount) external onlyRole(TREASURY_ADMIN) { }
}

contracts/payment-factory/interfaces/IAavePool.sol

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

/**
 * @title IAavePool
 * @notice Interface for Aave V3 Pool contract
 * @dev Used for integrating with Aave V3 lending protocol on Arbitrum
 */
interface IAavePool {
    /**
     * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens
     * @param asset The address of the underlying asset to supply
     * @param amount The amount to be supplied
     * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user wants to receive them on his own wallet
     * @param referralCode Code used to register the integrator originating the operation, for potential rewards (0 if no referral)
     */
    function supply(
        address asset,
        uint256 amount,
        address onBehalfOf,
        uint16 referralCode
    ) external;

    /**
     * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
     * @param asset The address of the underlying asset to withdraw
     * @param amount The underlying amount to be withdrawn (use type(uint256).max to withdraw all)
     * @param to The address that will receive the underlying, same as msg.sender if the user wants to receive it on his own wallet
     * @return The final amount withdrawn
     */
    function withdraw(
        address asset,
        uint256 amount,
        address to
    ) external returns (uint256);
}

contracts/payment-factory/interfaces/ICreditModule.sol

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

/**
 * @title ICreditModule
 * @notice Interface for credit module integration
 * @dev Payment contracts can integrate with credit modules to automatically deduct loan repayments
 */
interface ICreditModule {
    /**
     * @notice Process payment and calculate credit deduction
     * @param developer Address of the developer receiving payment
     * @param amount Amount of payment before credit deduction
     * @param token Payment token address (address(0) for ETH)
     * @return deductionAmount Amount to deduct for credit repayment
     */
    function processPayment(
        address developer,
        uint256 amount,
        address token
    ) external returns (uint256 deductionAmount);
    
    /**
     * @notice Get credit status for a developer
     * @param developer Address of the developer
     * @return outstanding Outstanding credit amount
     * @return repaymentPercent Percentage of each payment for repayment (basis points)
     * @return hasActiveCredit Whether developer has active credit
     */
    function getCreditStatus(address developer) 
        external 
        view 
        returns (
            uint256 outstanding,
            uint256 repaymentPercent,
            bool hasActiveCredit
        );
}

contracts/payment-factory/interfaces/IPaymentContract.sol

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

/**
 * @title IPaymentContract
 * @notice Interface for all payment contracts created by PaymentFactory
 */
interface IPaymentContract {
    
    struct PaymentInfo {
        uint256 amount;
        address token;
        address payer;
        uint256 timestamp;
        bool completed;
    }
    
    struct RecipientInfo {
        address recipient;
        uint256 share;        // Basis points
        uint256 totalReceived;
    }
    
    // Events
    event PaymentReceived(address indexed payer, uint256 amount, address token);
    event PaymentDistributed(address indexed recipient, uint256 amount, address token);
    event PlatformFeeCollected(uint256 amount, address token);
    event ContractStatusChanged(bool active);
    
    // Core functions
    function makePayment(uint256 _amount) external payable;
    function makeTokenPayment(address _token, uint256 _amount) external;
    function distributePayment(uint256 _paymentId) external;
    function withdrawRecipientFunds(address _recipient) external;
    
    // View functions
    function getRecipients() external view returns (RecipientInfo[] memory);
    function getPaymentHistory() external view returns (PaymentInfo[] memory);
    function getPendingAmount(address _recipient) external view returns (uint256);
    function getTotalDistributed() external view returns (uint256);
    function getPlatformFee() external view returns (uint256);
    function isActive() external view returns (bool);
    
    // Admin functions
    function setActive(bool _active) external;
    function emergencyWithdraw(address _token) external;
}

contracts/payment-factory/templates/EscrowContractV2.sol

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";

/// @dev The part of PaymentFactory's public `paymentContracts` getter read here (arrays are omitted by Solidity).
interface IEscrowFactoryRegistry {
    function paymentContracts(address contractAddress)
        external
        view
        returns (
            address registeredAddress,
            uint8 contractType,
            address creator,
            uint256 platformFee,
            uint256 createdAt,
            bool active
        );
}

/**
 * @title EscrowContractV2
 * @notice Milestone-based escrow whose released funds are split between payees by configurable shares - like
 *         FlexiblePaymentSplit - instead of v1's fixed developer / 3% HR / referrer / partner split.
 * @dev Derived from EscrowContract (v1, deployed with this factory). Kept from v1: the milestone lifecycle, review
 *      period and extensions, auto-release, the dispute flow (moderator + controller proposals, escalation, admin
 *      decision, dispute fees), admin refunds, creation-fee recovery, 2-step admin transfer, pause.
 *      Changed: payees + shares (sum 100%) receive each released milestone after the platform fee; the platform fee
 *      comes from the factory's template setting; one payee is the `developer` (work executor) who submits work.
 *      Removed: HR fee, referrer, partner, reputation vault, credit module, membership refunds.
 *      Function names and return shapes match v1 where the site reads them; payees are exposed as `getPayees()`
 *      (not `getRecipients()`, which the site uses to recognise FlexiblePaymentSplit).
 */
contract EscrowContractV2 is ReentrancyGuard, Pausable {
    using SafeERC20 for IERC20;

    enum MilestoneStatus {
        PENDING,        // Not funded yet
        FUNDED,         // Client deposited funds
        SUBMITTED,      // Developer submitted work
        APPROVED,       // Client approved, funds released
        DISPUTED,       // Client disputed the work
        CANCELLED,      // Cancelled before completion
        REFUNDED        // Funds returned to client / dispute settled
    }

    struct DisputeInfo {
        string reason;
        uint256 disputedAt;
        uint256 disputeDeadline;    // Arbiters must resolve by this time
        address moderator;
        address controller;
        bool resolved;
        bool moderatorProposed;
        uint256 moderatorClientAmount;
        uint256 moderatorDeveloperAmount;   // v1 name kept: the payees' side of the split
        bool controllerProposed;
        uint256 controllerClientAmount;
        uint256 controllerDeveloperAmount;
        bool moderatorRejected;
        bool controllerRejected;
        bool escalatedToAdmin;
    }

    struct Milestone {
        uint256 id;
        string description;
        uint256 amount;
        uint256 deadline;
        MilestoneStatus status;
        uint256 fundedAt;
        uint256 submittedAt;
        uint256 approvedAt;
        uint256 reviewDeadline;
        uint8 extensionCount;
        string submissionDetails;
    }

    struct Payee {
        address addr;
        uint256 share;          // Basis points; all shares sum to 10000
        uint256 totalReceived;
    }

    struct InitParams {
        address client;
        address developer;      // Work executor - must be one of the payees
        address platformTreasury;
        address paymentToken;   // ERC20 only (ETH escrow isn't supported)
        address admin;          // Dispute admin
        uint256 platformFeeBps; // From the factory template, e.g. 100 = 1%
        string projectName;
        string projectDescription;
    }

    // Participants
    address public creator;     // The factory (it initialises the clone)
    address public client;
    address public developer;
    address public platformTreasury;
    address public admin;
    address public pendingAdmin;
    address public paymentToken;

    Payee[] private payees;
    mapping(address => bool) public isPayee;

    // Fees
    uint256 public platformFeeBps;
    uint256 public constant MAX_PLATFORM_FEE = 1000;     // 10% ceiling, as the factory's maxPlatformFee
    uint256 public constant DISPUTE_FEE = 1000;          // 10% total dispute fee
    uint256 public constant DISPUTE_MODERATOR_FEE = 500; // 5% to moderator + controller
    uint256 public constant DISPUTE_PLATFORM_FEE = 500;  // 5% to platform
    uint256 public constant BASIS_POINTS = 10000;

    // Review settings
    uint256 public constant REVIEW_PERIOD = 7 days;
    uint256 public constant EXTENSION_PERIOD = 7 days;
    uint8 public constant MAX_EXTENSIONS = 3;
    uint256 public constant ARBITRATION_PERIOD = 14 days;

    // Milestones and disputes
    Milestone[] public milestones;
    uint256 public totalMilestones;
    uint256 public completedMilestones;
    uint256 public totalProjectValue;
    mapping(uint256 => DisputeInfo) public disputes;

    // Revenue tracking
    uint256 public platformRevenueTotal;
    uint256 public payeesRevenueTotal;

    // Metadata
    string public projectName;
    string public projectDescription;
    uint256 public createdAt;
    bool public initialized;

    // Creation fee recovery
    uint256 public creationFee;
    bool public creationFeeRecovered;

    // Events (v1 names and shapes kept where they still apply)
    event MilestoneCreated(uint256 indexed milestoneId, string description, uint256 amount, uint256 deadline);
    event MilestoneFunded(uint256 indexed milestoneId, uint256 amount);
    event MilestoneSubmitted(uint256 indexed milestoneId, string submissionDetails);
    event MilestoneApproved(uint256 indexed milestoneId, uint256 amountReleased);
    event MilestoneDisputed(uint256 indexed milestoneId, string reason, uint256 disputeDeadline);
    event ModeratorAssigned(uint256 indexed milestoneId, address moderator, address controller);
    event DisputeProposedByModerator(uint256 indexed milestoneId, uint256 clientAmount, uint256 developerAmount);
    event DisputeProposedByController(uint256 indexed milestoneId, uint256 clientAmount, uint256 developerAmount);
    event DisputeProposalRejected(uint256 indexed milestoneId, address indexed rejectedBy, string reason);
    event DisputeEscalatedToAdmin(uint256 indexed milestoneId, string reason);
    event DisputeResolvedByConsensus(uint256 indexed milestoneId, uint256 clientAmount, uint256 developerAmount);
    event DisputeResolvedByAdmin(uint256 indexed milestoneId, uint256 clientAmount, uint256 developerAmount);
    event DisputeResolved(uint256 indexed milestoneId, bool releasedToDeveloper, uint256 moderatorFee, uint256 platformFee);
    event DisputeSplitApplied(uint256 indexed milestoneId, uint256 clientAmount, uint256 developerAmount);
    event MilestoneCancelled(uint256 indexed milestoneId);
    event MilestoneRefunded(uint256 indexed milestoneId, uint256 amount);
    event ReviewExtensionRequested(uint256 indexed milestoneId, uint256 newDeadline);
    event CreationFeeRecovered(uint256 amount);
    event PayeePaid(address indexed payee, uint256 amount);
    event AdminTransferInitiated(address indexed currentAdmin, address indexed newAdmin);
    event AdminTransferred(address indexed oldAdmin, address indexed newAdmin);

    modifier onlyClient() {
        require(msg.sender == client, "Only client");
        _;
    }

    modifier onlyDeveloper() {
        require(msg.sender == developer, "Only developer");
        _;
    }

    modifier onlyAdmin() {
        require(msg.sender == admin, "Only admin");
        _;
    }

    modifier onlyModerator(uint256 _milestoneId) {
        require(msg.sender == disputes[_milestoneId].moderator, "Only assigned moderator");
        _;
    }

    modifier validMilestone(uint256 _milestoneId) {
        require(_milestoneId < milestones.length, "Invalid milestone");
        _;
    }

    /// @custom:oz-upgrades-unsafe-allow constructor
    /// @dev Locks the implementation so initialize() only ever succeeds on clones.
    constructor() {
        initialized = true;
    }

    /**
     * @notice Initialize the escrow (called by the factory on a fresh clone)
     * @param _payees Addresses that receive released milestones
     * @param _shares Their shares in basis points; must sum to 10000
     */
    function initialize(InitParams calldata params, address[] calldata _payees, uint256[] calldata _shares) external {
        require(!initialized, "Already initialized");
        require(params.client != address(0), "Invalid client");
        require(params.platformTreasury != address(0), "Invalid platform treasury");
        require(params.paymentToken != address(0), "ERC20 payment token required");
        require(params.admin != address(0), "Invalid admin");
        require(params.platformFeeBps <= MAX_PLATFORM_FEE, "Platform fee too high");
        require(_payees.length > 0 && _payees.length == _shares.length, "Invalid payees");

        uint256 totalShares;
        for (uint256 i = 0; i < _payees.length; i++) {
            require(_payees[i] != address(0), "Invalid payee");
            require(_shares[i] > 0, "Invalid share");
            require(!isPayee[_payees[i]], "Duplicate payee");
            isPayee[_payees[i]] = true;
            payees.push(Payee({addr: _payees[i], share: _shares[i], totalReceived: 0}));
            totalShares += _shares[i];
        }
        require(totalShares == BASIS_POINTS, "Shares must sum to 100%");
        require(isPayee[params.developer], "Developer must be a payee");

        creator = msg.sender;
        client = params.client;
        developer = params.developer;
        platformTreasury = params.platformTreasury;
        paymentToken = params.paymentToken;
        admin = params.admin;
        platformFeeBps = params.platformFeeBps;
        projectName = params.projectName;
        projectDescription = params.projectDescription;
        createdAt = block.timestamp;
        initialized = true;
    }

    // ============ Milestone lifecycle (as v1) ============

    function addMilestone(string memory _description, uint256 _amount, uint256 _deadline) external onlyClient {
        require(_amount > 0, "Amount must be > 0");
        require(_deadline > block.timestamp, "Deadline must be in future");
        require(bytes(_description).length > 0, "Description required");

        uint256 milestoneId = milestones.length;
        milestones.push(
            Milestone({
                id: milestoneId,
                description: _description,
                amount: _amount,
                deadline: _deadline,
                status: MilestoneStatus.PENDING,
                fundedAt: 0,
                submittedAt: 0,
                approvedAt: 0,
                reviewDeadline: 0,
                extensionCount: 0,
                submissionDetails: ""
            })
        );
        totalMilestones++;
        totalProjectValue += _amount;

        emit MilestoneCreated(milestoneId, _description, _amount, _deadline);
    }

    function fundMilestone(uint256 _milestoneId) external onlyClient nonReentrant validMilestone(_milestoneId) {
        Milestone storage milestone = milestones[_milestoneId];
        require(milestone.status == MilestoneStatus.PENDING, "Already funded or completed");

        IERC20(paymentToken).safeTransferFrom(msg.sender, address(this), milestone.amount);
        milestone.status = MilestoneStatus.FUNDED;
        milestone.fundedAt = block.timestamp;

        emit MilestoneFunded(_milestoneId, milestone.amount);
    }

    function submitMilestone(uint256 _milestoneId, string memory _submissionDetails)
        external
        onlyDeveloper
        validMilestone(_milestoneId)
    {
        Milestone storage milestone = milestones[_milestoneId];
        require(milestone.status == MilestoneStatus.FUNDED, "Not funded");
        require(bytes(_submissionDetails).length > 0, "Submission details required");

        milestone.status = MilestoneStatus.SUBMITTED;
        milestone.submittedAt = block.timestamp;
        milestone.reviewDeadline = block.timestamp + REVIEW_PERIOD;
        milestone.submissionDetails = _submissionDetails;

        emit MilestoneSubmitted(_milestoneId, _submissionDetails);
    }

    function approveMilestone(uint256 _milestoneId) external onlyClient nonReentrant validMilestone(_milestoneId) {
        require(milestones[_milestoneId].status == MilestoneStatus.SUBMITTED, "Not submitted");
        _releaseMilestoneFunds(_milestoneId);
    }

    function autoReleaseMilestone(uint256 _milestoneId) external nonReentrant validMilestone(_milestoneId) {
        Milestone storage milestone = milestones[_milestoneId];
        require(milestone.status == MilestoneStatus.SUBMITTED, "Not submitted");
        require(block.timestamp > milestone.reviewDeadline, "Review period not expired");
        _releaseMilestoneFunds(_milestoneId);
    }

    function requestReviewExtension(uint256 _milestoneId) external onlyClient validMilestone(_milestoneId) {
        Milestone storage milestone = milestones[_milestoneId];
        require(milestone.status == MilestoneStatus.SUBMITTED, "Not submitted");
        require(milestone.extensionCount < MAX_EXTENSIONS, "Max extensions reached");
        require(block.timestamp <= milestone.reviewDeadline, "Review period expired");

        milestone.extensionCount++;
        milestone.reviewDeadline += EXTENSION_PERIOD;

        emit ReviewExtensionRequested(_milestoneId, milestone.reviewDeadline);
    }

    function cancelMilestone(uint256 _milestoneId) external onlyClient validMilestone(_milestoneId) {
        Milestone storage milestone = milestones[_milestoneId];
        require(milestone.status == MilestoneStatus.PENDING, "Can only cancel pending milestones");
        milestone.status = MilestoneStatus.CANCELLED;
        emit MilestoneCancelled(_milestoneId);
    }

    /// @notice Refund a funded or disputed milestone to the client in full - admin only (as v1)
    function refundMilestone(uint256 _milestoneId) external onlyAdmin nonReentrant validMilestone(_milestoneId) {
        Milestone storage milestone = milestones[_milestoneId];
        require(
            milestone.status == MilestoneStatus.FUNDED || milestone.status == MilestoneStatus.DISPUTED,
            "Cannot refund"
        );
        _transferFunds(client, milestone.amount);
        milestone.status = MilestoneStatus.REFUNDED;
        emit MilestoneRefunded(_milestoneId, milestone.amount);
    }

    // ============ Disputes (as v1; the payees' side is split by shares) ============

    function disputeMilestone(uint256 _milestoneId, string memory _reason) external onlyClient validMilestone(_milestoneId) {
        Milestone storage milestone = milestones[_milestoneId];
        require(milestone.status == MilestoneStatus.SUBMITTED, "Not submitted");
        require(block.timestamp <= milestone.reviewDeadline, "Review period expired");

        milestone.status = MilestoneStatus.DISPUTED;
        uint256 disputeDeadline = block.timestamp + ARBITRATION_PERIOD;
        DisputeInfo storage dispute = disputes[_milestoneId];
        dispute.reason = _reason;
        dispute.disputedAt = block.timestamp;
        dispute.disputeDeadline = disputeDeadline;

        emit MilestoneDisputed(_milestoneId, _reason, disputeDeadline);
    }

    function assignModerator(uint256 _milestoneId, address _moderator, address _controller)
        external
        onlyAdmin
        validMilestone(_milestoneId)
    {
        require(milestones[_milestoneId].status == MilestoneStatus.DISPUTED, "Not disputed");
        require(_moderator != address(0), "Invalid moderator");
        require(_controller != address(0), "Invalid controller");
        require(!disputes[_milestoneId].resolved, "Already resolved");

        disputes[_milestoneId].moderator = _moderator;
        disputes[_milestoneId].controller = _controller;
        emit ModeratorAssigned(_milestoneId, _moderator, _controller);
    }

    /// @param _developerAmount The payees' side of the split (shared between payees by their shares)
    function proposeResolutionByModerator(uint256 _milestoneId, uint256 _clientAmount, uint256 _developerAmount)
        external
        onlyModerator(_milestoneId)
        nonReentrant
        validMilestone(_milestoneId)
    {
        DisputeInfo storage dispute = _openDispute(_milestoneId, _clientAmount, _developerAmount);
        dispute.moderatorProposed = true;
        dispute.moderatorClientAmount = _clientAmount;
        dispute.moderatorDeveloperAmount = _developerAmount;
        dispute.moderatorRejected = false;

        if (
            dispute.controllerProposed &&
            dispute.controllerClientAmount == _clientAmount &&
            dispute.controllerDeveloperAmount == _developerAmount
        ) {
            _executeDisputeResolution(_milestoneId, _clientAmount, _developerAmount);
            emit DisputeResolvedByConsensus(_milestoneId, _clientAmount, _developerAmount);
        } else {
            emit DisputeProposedByModerator(_milestoneId, _clientAmount, _developerAmount);
        }
    }

    function proposeResolutionByController(uint256 _milestoneId, uint256 _clientAmount, uint256 _developerAmount)
        external
        nonReentrant
        validMilestone(_milestoneId)
    {
        require(msg.sender == disputes[_milestoneId].controller, "Only controller");
        DisputeInfo storage dispute = _openDispute(_milestoneId, _clientAmount, _developerAmount);
        dispute.controllerProposed = true;
        dispute.controllerClientAmount = _clientAmount;
        dispute.controllerDeveloperAmount = _developerAmount;
        dispute.controllerRejected = false;

        if (
            dispute.moderatorProposed &&
            dispute.moderatorClientAmount == _clientAmount &&
            dispute.moderatorDeveloperAmount == _developerAmount
        ) {
            _executeDisputeResolution(_milestoneId, _clientAmount, _developerAmount);
            emit DisputeResolvedByConsensus(_milestoneId, _clientAmount, _developerAmount);
        } else {
            emit DisputeProposedByController(_milestoneId, _clientAmount, _developerAmount);
        }
    }

    function rejectControllerProposal(uint256 _milestoneId, string memory _reason)
        external
        onlyModerator(_milestoneId)
        validMilestone(_milestoneId)
    {
        DisputeInfo storage dispute = disputes[_milestoneId];
        require(!dispute.resolved, "Already resolved");
        require(!dispute.escalatedToAdmin, "Already escalated");
        require(dispute.controllerProposed, "No controller proposal");
        dispute.moderatorRejected = true;
        emit DisputeProposalRejected(_milestoneId, dispute.moderator, _reason);
    }

    function rejectModeratorProposal(uint256 _milestoneId, string memory _reason) external validMilestone(_milestoneId) {
        DisputeInfo storage dispute = disputes[_milestoneId];
        require(msg.sender == dispute.controller, "Only controller");
        require(!dispute.resolved, "Already resolved");
        require(!dispute.escalatedToAdmin, "Already escalated");
        require(dispute.moderatorProposed, "No moderator proposal");
        dispute.controllerRejected = true;
        emit DisputeProposalRejected(_milestoneId, dispute.controller, _reason);
    }

    function escalateDisputeToAdmin(uint256 _milestoneId, string memory _reason) external validMilestone(_milestoneId) {
        DisputeInfo storage dispute = disputes[_milestoneId];
        require(msg.sender == dispute.moderator || msg.sender == dispute.controller, "Only moderator or controller");
        require(!dispute.resolved, "Already resolved");
        require(!dispute.escalatedToAdmin, "Already escalated");
        require(dispute.moderatorProposed && dispute.controllerProposed, "Both must propose first");
        require(
            dispute.moderatorClientAmount != dispute.controllerClientAmount ||
                dispute.moderatorDeveloperAmount != dispute.controllerDeveloperAmount,
            "Proposals match, no need to escalate"
        );
        dispute.escalatedToAdmin = true;
        emit DisputeEscalatedToAdmin(_milestoneId, _reason);
    }

    function resolveDisputeByAdmin(uint256 _milestoneId, uint256 _clientAmount, uint256 _developerAmount)
        external
        onlyAdmin
        nonReentrant
        validMilestone(_milestoneId)
    {
        DisputeInfo storage dispute = disputes[_milestoneId];
        require(milestones[_milestoneId].status == MilestoneStatus.DISPUTED, "Not disputed");
        require(!dispute.resolved, "Already resolved");
        require(dispute.escalatedToAdmin, "Not escalated to admin");
        require(
            _clientAmount + _developerAmount == _calculateAvailableForSplit(milestones[_milestoneId].amount),
            "Invalid split amounts"
        );
        _executeDisputeResolution(_milestoneId, _clientAmount, _developerAmount);
        emit DisputeResolvedByAdmin(_milestoneId, _clientAmount, _developerAmount);
    }

    // ============ Admin / factory ============

    /// @notice Set the creation fee to recover from the first release (called by the factory when paid later)
    function setCreationFee(uint256 _fee) external {
        require(msg.sender == creator, "Only creator can set creation fee");
        require(!creationFeeRecovered, "Creation fee already recovered");
        creationFee = _fee;
    }

    function transferAdmin(address _newAdmin) external onlyAdmin {
        require(_newAdmin != address(0), "Invalid admin address");
        require(_newAdmin != admin, "Already current admin");
        pendingAdmin = _newAdmin;
        emit AdminTransferInitiated(admin, _newAdmin);
    }

    function acceptAdmin() external {
        require(msg.sender == pendingAdmin, "Only pending admin");
        address oldAdmin = admin;
        admin = pendingAdmin;
        pendingAdmin = address(0);
        emit AdminTransferred(oldAdmin, admin);
    }

    function pause() external onlyAdmin {
        _pause();
    }

    function unpause() external onlyAdmin {
        _unpause();
    }

    // ============ Views ============

    /// @notice Template version: 2 = payees with shares, platform fee from the factory. (v1 has no `version()`.)
    function version() external pure returns (uint256) {
        return 2;
    }

    /// @notice The wallet that created this escrow through the factory (e.g. an agency's manager).
    function manager() public view returns (address) {
        (, , address factoryCreator, , , ) = IEscrowFactoryRegistry(creator).paymentContracts(address(this));
        return factoryCreator;
    }

    function getPayees() external view returns (Payee[] memory) {
        return payees;
    }

    function getMilestone(uint256 _milestoneId) external view validMilestone(_milestoneId) returns (Milestone memory) {
        return milestones[_milestoneId];
    }

    function getAllMilestones() external view returns (Milestone[] memory) {
        return milestones;
    }

    function getMilestoneCount() external view returns (uint256) {
        return milestones.length;
    }

    /// @dev v1 shape; the third field (v1's HR agent) is now the manager.
    function getContractInfo()
        external
        view
        returns (
            address _client,
            address _developer,
            address _manager,
            string memory _projectName,
            uint256 _totalMilestones,
            uint256 _completedMilestones
        )
    {
        return (client, developer, manager(), projectName, totalMilestones, completedMilestones);
    }

    function isCompleted() external view returns (bool) {
        return totalMilestones > 0 && completedMilestones == totalMilestones;
    }

    /// @dev v1 shape; the last field (v1's HR revenue) is now what all payees received.
    function getStats()
        external
        view
        returns (
            uint256 _totalMilestones,
            uint256 _completedMilestones,
            uint256 _totalProjectValue,
            uint256 _platformRevenue,
            uint256 _payeesRevenue
        )
    {
        return (totalMilestones, completedMilestones, totalProjectValue, platformRevenueTotal, payeesRevenueTotal);
    }

    function getDisputeInfo(uint256 _milestoneId)
        external
        view
        returns (
            string memory reason,
            uint256 disputedAt,
            uint256 disputeDeadline,
            address moderator,
            address controller,
            bool resolved,
            bool escalatedToAdmin
        )
    {
        DisputeInfo storage d = disputes[_milestoneId];
        return (d.reason, d.disputedAt, d.disputeDeadline, d.moderator, d.controller, d.resolved, d.escalatedToAdmin);
    }

    function getDisputeProposals(uint256 _milestoneId)
        external
        view
        returns (
            bool moderatorProposed,
            uint256 moderatorClientAmount,
            uint256 moderatorDeveloperAmount,
            bool controllerProposed,
            uint256 controllerClientAmount,
            uint256 controllerDeveloperAmount,
            bool moderatorRejected,
            bool controllerRejected
        )
    {
        DisputeInfo storage d = disputes[_milestoneId];
        return (
            d.moderatorProposed,
            d.moderatorClientAmount,
            d.moderatorDeveloperAmount,
            d.controllerProposed,
            d.controllerClientAmount,
            d.controllerDeveloperAmount,
            d.moderatorRejected,
            d.controllerRejected
        );
    }

    /// @notice Amounts of a dispute settlement (v1 shape)
    function calculateDisputeAmounts(uint256 _milestoneId)
        external
        view
        validMilestone(_milestoneId)
        returns (
            uint256 platformFees,
            uint256 disputeFees,
            uint256 availableForSplit,
            uint256 moderatorShare,
            uint256 controllerShare,
            uint256 platformDisputeFee
        )
    {
        uint256 totalAmount = milestones[_milestoneId].amount;
        platformFees = _calculateTotalPlatformFees(totalAmount);
        uint256 afterPlatformFees = totalAmount - platformFees;
        uint256 totalModeratorFee = (afterPlatformFees * DISPUTE_MODERATOR_FEE) / BASIS_POINTS;
        platformDisputeFee = (afterPlatformFees * DISPUTE_PLATFORM_FEE) / BASIS_POINTS;
        disputeFees = totalModeratorFee + platformDisputeFee;
        moderatorShare = totalModeratorFee / 2;
        controllerShare = totalModeratorFee - moderatorShare;
        availableForSplit = afterPlatformFees - disputeFees;
    }

    /// @dev v1 shape; v1's HR / partner / referrer fields are always 0 here.
    function getDisputePaymentBreakdown(uint256 _milestoneId)
        external
        view
        validMilestone(_milestoneId)
        returns (
            uint256 disputePlatformRevenue,
            uint256 hrPayment,
            uint256 partnerPayment,
            uint256 referrerPayment,
            uint256 moderatorPayment,
            uint256 controllerPayment,
            uint256 totalFeesDeducted,
            uint256 remainingForParties
        )
    {
        uint256 totalAmount = milestones[_milestoneId].amount;
        uint256 platformFees = _calculateTotalPlatformFees(totalAmount);
        uint256 afterPlatformFees = totalAmount - platformFees;
        uint256 totalModeratorFee = (afterPlatformFees * DISPUTE_MODERATOR_FEE) / BASIS_POINTS;
        uint256 platformDisputeFee = (afterPlatformFees * DISPUTE_PLATFORM_FEE) / BASIS_POINTS;

        moderatorPayment = totalModeratorFee / 2;
        controllerPayment = totalModeratorFee - moderatorPayment;
        disputePlatformRevenue = platformFees + platformDisputeFee;
        totalFeesDeducted = platformFees + totalModeratorFee + platformDisputeFee;
        remainingForParties = totalAmount - totalFeesDeducted;
        (hrPayment, partnerPayment, referrerPayment) = (0, 0, 0);
    }

    // ============ Internal ============

    /// @dev Shared checks of both dispute proposals (as v1)
    function _openDispute(uint256 _milestoneId, uint256 _clientAmount, uint256 _developerAmount)
        internal
        view
        returns (DisputeInfo storage dispute)
    {
        dispute = disputes[_milestoneId];
        require(milestones[_milestoneId].status == MilestoneStatus.DISPUTED, "Not disputed");
        require(!dispute.resolved, "Already resolved");
        require(!dispute.escalatedToAdmin, "Already escalated to admin");
        require(block.timestamp <= dispute.disputeDeadline, "Arbitration period expired");
        require(
            _clientAmount + _developerAmount == _calculateAvailableForSplit(milestones[_milestoneId].amount),
            "Invalid split amounts"
        );
    }

    /// @dev Approve / auto-release: creation fee first (if still owed), then the platform fee, then payees by share.
    function _releaseMilestoneFunds(uint256 _milestoneId) internal {
        Milestone storage milestone = milestones[_milestoneId];
        uint256 totalAmount = milestone.amount;

        if (!creationFeeRecovered && creationFee > 0) {
            uint256 feeToRecover = creationFee > totalAmount ? totalAmount : creationFee;
            _transferToTreasury(feeToRecover);
            totalAmount -= feeToRecover;
            creationFeeRecovered = true;
            emit CreationFeeRecovered(feeToRecover);
        }

        uint256 platformFeeAmount = (totalAmount * platformFeeBps) / BASIS_POINTS;
        _transferToTreasury(platformFeeAmount);
        platformRevenueTotal += platformFeeAmount;

        uint256 released = totalAmount - platformFeeAmount;
        _payPayees(released);

        milestone.status = MilestoneStatus.APPROVED;
        milestone.approvedAt = block.timestamp;
        completedMilestones++;

        emit MilestoneApproved(_milestoneId, released);
    }

    function _executeDisputeResolution(uint256 _milestoneId, uint256 _clientAmount, uint256 _developerAmount) internal {
        disputes[_milestoneId].resolved = true;
        uint256 milestoneAmount = milestones[_milestoneId].amount;

        _payDisputeFees(_milestoneId);
        if (_clientAmount > 0) _transferFunds(client, _clientAmount);
        if (_developerAmount > 0) _payPayees(_developerAmount);
        _payPlatformFees(milestoneAmount);

        milestones[_milestoneId].status = MilestoneStatus.REFUNDED;
        emit DisputeSplitApplied(_milestoneId, _clientAmount, _developerAmount);
    }

    function _payDisputeFees(uint256 _milestoneId) internal {
        DisputeInfo storage dispute = disputes[_milestoneId];
        uint256 totalAmount = milestones[_milestoneId].amount;
        uint256 afterPlatform = totalAmount - _calculateTotalPlatformFees(totalAmount);

        uint256 totalDisputeFee = (afterPlatform * DISPUTE_MODERATOR_FEE) / BASIS_POINTS;
        uint256 platformDisputeFee = (afterPlatform * DISPUTE_PLATFORM_FEE) / BASIS_POINTS;

        _transferFunds(dispute.moderator, totalDisputeFee / 2);
        _transferFunds(dispute.controller, totalDisputeFee - (totalDisputeFee / 2));
        _transferToTreasury(platformDisputeFee);
        platformRevenueTotal += platformDisputeFee;

        emit DisputeResolved(_milestoneId, true, totalDisputeFee, platformDisputeFee);
    }

    /// @dev The platform fee (and creation fee, if still owed) of a dispute-settled milestone (as v1)
    function _payPlatformFees(uint256 _milestoneAmount) internal {
        uint256 platformAmount = (_milestoneAmount * platformFeeBps) / BASIS_POINTS;
        _transferToTreasury(platformAmount);
        platformRevenueTotal += platformAmount;

        if (!creationFeeRecovered && creationFee > 0) {
            _transferToTreasury(creationFee);
            creationFeeRecovered = true;
            emit CreationFeeRecovered(creationFee);
        }
    }

    /// @dev Splits `_amount` between payees by share; rounding dust goes to the last payee so nothing stays behind.
    function _payPayees(uint256 _amount) internal {
        uint256 paid;
        uint256 last = payees.length - 1;
        for (uint256 i = 0; i < payees.length; i++) {
            uint256 part = i == last ? _amount - paid : (_amount * payees[i].share) / BASIS_POINTS;
            paid += part;
            if (part > 0) {
                payees[i].totalReceived += part;
                _transferFunds(payees[i].addr, part);
                emit PayeePaid(payees[i].addr, part);
            }
        }
        payeesRevenueTotal += _amount;
    }

    /// @dev Platform fee + unrecovered creation fee of `_amount` (dispute math, as v1 without HR/partner/referrer)
    function _calculateTotalPlatformFees(uint256 _amount) internal view returns (uint256 totalFees) {
        totalFees = (_amount * platformFeeBps) / BASIS_POINTS;
        if (!creationFeeRecovered && creationFee > 0) {
            totalFees += creationFee;
        }
    }

    function _calculateAvailableForSplit(uint256 _amount) internal view returns (uint256) {
        uint256 afterPlatform = _amount - _calculateTotalPlatformFees(_amount);
        uint256 moderatorFee = (afterPlatform * DISPUTE_MODERATOR_FEE) / BASIS_POINTS;
        uint256 platformDisputeFee = (afterPlatform * DISPUTE_PLATFORM_FEE) / BASIS_POINTS;
        return afterPlatform - moderatorFee - platformDisputeFee;
    }

    function _transferFunds(address _to, uint256 _amount) internal {
        if (_amount == 0) return;
        IERC20(paymentToken).safeTransfer(_to, _amount);
    }

    function _transferToTreasury(uint256 _amount) internal {
        if (_amount == 0) return;
        IERC20(paymentToken).safeTransfer(platformTreasury, _amount);
    }
}

contracts/payment-factory/templates/FlexiblePaymentSplit.sol

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

/// @dev The part of PaymentFactory's public `paymentContracts` getter this template reads (arrays are omitted by Solidity).
interface IPaymentFactoryRegistry {
    function paymentContracts(address contractAddress)
        external
        view
        returns (
            address registeredAddress,
            uint8 contractType,
            address creator,
            uint256 platformFee,
            uint256 createdAt,
            bool active
        );
}

/**
 * @title FlexiblePaymentSplit
 * @notice Flexible payment splitting contract with configurable recipients
 * @dev Supports both direct transfer and claim mechanisms. Uses clone pattern.
 *      v2: the wallet that created the contract through the factory (its "manager", e.g. an agency setting up
 *      contracts for its clients) may also create payment requests. It still can't move funds.
 */
contract FlexiblePaymentSplit is ReentrancyGuard {
    using SafeERC20 for IERC20;

    // Payment distribution mode
    enum DistributionMode {
        DIRECT_TRANSFER,  // Funds sent directly to recipients
        CLAIM_BASED       // Recipients must claim their funds
    }

    struct Recipient {
        address addr;
        uint256 share; // Basis points (10000 = 100%)
        uint256 totalReceived;
        uint256 pendingBalance;
    }

    struct PaymentRequest {
        uint256 id;
        uint256 amount;
        string description;
        uint256 createdAt;
        bool isPaid;
        bool isCancelled;
        address createdBy;
        address requestedFrom; // Who should fulfill this request (typically client)
    }

    struct InitParams {
        address client;
        address paymentToken;
        address treasury;
        DistributionMode mode;
        uint256 creationFee;
        bool payCreationFeeNow;
    }

    // Contract configuration
    address public paymentToken;
    address public factory;
    address public treasury;
    address public client;
    DistributionMode public distributionMode;
    
    // Creation fee configuration
    uint256 public creationFee;
    bool public creationFeePaidUpfront;
    bool public creationFeeRecovered;
    
    // Platform fee (1% = 100 basis points)
    uint256 public constant PLATFORM_FEE_BPS = 100;
    uint256 public constant MAX_BPS = 10000;
    
    // Recipients
    Recipient[] public recipients;
    mapping(address => uint256) public recipientIndex;
    mapping(address => bool) public isRecipient;
    
    // Payment tracking
    uint256 public totalDeposited;
    uint256 public totalDistributed;
    uint256 public platformFeesCollected;
    // Sum of all recipients' unclaimed pendingBalance - funds already owed and reserved,
    // must never be re-processed as "new" income by distributeBalance()
    uint256 public totalPendingBalance;
    
    // Off-chain payment requests
    PaymentRequest[] public paymentRequests;
    uint256 public nextRequestId;
    
    // Status
    bool public active;
    bool private initialized;

    // Events
    event PaymentReceived(address indexed from, uint256 amount, uint256 platformFee);
    event FundsDistributed(address indexed recipient, uint256 amount);
    event FundsClaimed(address indexed recipient, uint256 amount);
    event PaymentRequestCreated(uint256 indexed requestId, uint256 amount, string description, address createdBy);
    event PaymentRequestFulfilled(uint256 indexed requestId, address paidBy);
    event PaymentRequestCancelled(uint256 indexed requestId, address cancelledBy);
    event CreationFeeRecovered(uint256 amount);
    event ClientUpdated(address indexed oldClient, address indexed newClient);
    event ContractDeactivated();

    // Errors
    error Unauthorized();
    error InvalidConfiguration();
    error InsufficientBalance();
    error TransferFailed();
    error ContractInactive();
    error InvalidRecipient();
    error InvalidShare();
    error PaymentRequestNotFound();
    error PaymentRequestAlreadyPaid();
    error PaymentRequestAlreadyCancelled();
    error AlreadyInitialized();

    /// @custom:oz-upgrades-unsafe-allow constructor
    /// @dev Locks the master/implementation contract so initialize() can only ever
    ///      succeed on clones (which get their own fresh storage via delegatecall).
    constructor() {
        initialized = true;
    }

    /**
     * @notice Initialize the contract (replaces constructor for clone pattern)
     * @param params Initialization parameters
     * @param _recipients Array of recipient addresses
     * @param _shares Array of shares in basis points (must sum to 10000)
     */
    function initialize(
        InitParams calldata params,
        address[] calldata _recipients,
        uint256[] calldata _shares
    ) external {
        if (initialized) revert AlreadyInitialized();
        if (_recipients.length == 0 || _recipients.length != _shares.length) {
            revert InvalidConfiguration();
        }
        
        // Validate total shares = 100%
        uint256 totalShares = 0;
        for (uint256 i = 0; i < _shares.length; i++) {
            totalShares += _shares[i];
            if (_recipients[i] == address(0)) revert InvalidRecipient();
            if (_shares[i] == 0) revert InvalidShare();
        }
        if (totalShares != MAX_BPS) revert InvalidConfiguration();

        client = params.client;
        paymentToken = params.paymentToken;
        factory = msg.sender; // Factory calls initialize
        treasury = params.treasury;
        distributionMode = params.mode;
        creationFee = params.creationFee;
        creationFeePaidUpfront = params.payCreationFeeNow;
        nextRequestId = 1;
        active = true;
        initialized = true;

        // Initialize recipients
        for (uint256 i = 0; i < _recipients.length; i++) {
            recipients.push(Recipient({
                addr: _recipients[i],
                share: _shares[i],
                totalReceived: 0,
                pendingBalance: 0
            }));
            recipientIndex[_recipients[i]] = i;
            isRecipient[_recipients[i]] = true;
        }

        // Note: Creation fee is handled by PaymentFactory, not here
        // If payCreationFeeNow is true, fee is already paid by Factory
        // If false, fee will be deducted from first payment via _processPayment
        if (params.payCreationFeeNow && params.creationFee > 0) {
            creationFeeRecovered = true; // Mark as recovered since Factory already paid
        }
    }

    /**
     * @notice Make a payment to the contract
     * @param amount Amount to pay (in payment token)
     */
    function makePayment(uint256 amount) external nonReentrant {
        if (!active) revert ContractInactive();
        if (amount == 0) revert InvalidConfiguration();

        // Transfer tokens from sender
        IERC20(paymentToken).safeTransferFrom(msg.sender, address(this), amount);
        
        _processPayment(amount);
    }

    /**
     * @notice Internal function to process payment
     * @param amount Amount to process
     */
    function _processPayment(uint256 amount) internal {
        uint256 remainingAmount = amount;
        
        // Deduct creation fee if not yet recovered
        if (!creationFeeRecovered && creationFee > 0) {
            if (amount < creationFee) revert InsufficientBalance();
            IERC20(paymentToken).safeTransfer(treasury, creationFee);
            remainingAmount -= creationFee;
            creationFeeRecovered = true;
            emit CreationFeeRecovered(creationFee);
        }
        
        // Calculate and collect platform fee (1%)
        uint256 platformFee = (remainingAmount * PLATFORM_FEE_BPS) / MAX_BPS;
        IERC20(paymentToken).safeTransfer(treasury, platformFee);
        platformFeesCollected += platformFee;
        
        // Amount to distribute to recipients
        uint256 amountToDistribute = remainingAmount - platformFee;
        totalDeposited += amount;
        
        emit PaymentReceived(msg.sender, amount, platformFee);
        
        // Distribute to recipients based on mode
        if (distributionMode == DistributionMode.DIRECT_TRANSFER) {
            _distributeDirectly(amountToDistribute);
        } else {
            _addToPendingBalances(amountToDistribute);
        }
    }

    /**
     * @notice Distribute funds directly to recipients
     */
    function _distributeDirectly(uint256 amount) private {
        for (uint256 i = 0; i < recipients.length; i++) {
            uint256 recipientAmount = (amount * recipients[i].share) / MAX_BPS;
            recipients[i].totalReceived += recipientAmount;
            totalDistributed += recipientAmount;
            
            IERC20(paymentToken).safeTransfer(recipients[i].addr, recipientAmount);
            emit FundsDistributed(recipients[i].addr, recipientAmount);
        }
    }

    /**
     * @notice Add funds to pending balances for claim
     */
    function _addToPendingBalances(uint256 amount) private {
        for (uint256 i = 0; i < recipients.length; i++) {
            uint256 recipientAmount = (amount * recipients[i].share) / MAX_BPS;
            recipients[i].pendingBalance += recipientAmount;
            recipients[i].totalReceived += recipientAmount;
            totalPendingBalance += recipientAmount;
        }
    }

    /**
     * @notice Claim pending funds (only in CLAIM_BASED mode)
     */
    function claimFunds() external nonReentrant {
        if (!active) revert ContractInactive();
        if (distributionMode != DistributionMode.CLAIM_BASED) revert InvalidConfiguration();
        if (!isRecipient[msg.sender]) revert InvalidRecipient();
        
        uint256 idx = recipientIndex[msg.sender];
        uint256 amount = recipients[idx].pendingBalance;
        
        if (amount == 0) revert InsufficientBalance();
        
        recipients[idx].pendingBalance = 0;
        totalPendingBalance -= amount;
        totalDistributed += amount;
        
        IERC20(paymentToken).safeTransfer(msg.sender, amount);
        emit FundsClaimed(msg.sender, amount);
    }

    /**
     * @notice Distribute any tokens that were sent directly to the contract, excluding
     *         funds already reserved for unclaimed CLAIM_BASED pendingBalance.
     * @dev Anyone can call this to trigger distribution of accumulated balance. Only the
     *      excess over totalPendingBalance is processed, so this can never re-skim fees
     *      from, or double-count, tokens that recipients have not claimed yet.
     */
    function distributeBalance() external nonReentrant {
        if (!active) revert ContractInactive();
        
        uint256 balance = IERC20(paymentToken).balanceOf(address(this));
        uint256 reserved = totalPendingBalance;
        if (balance <= reserved) revert InsufficientBalance();

        uint256 excess = balance - reserved;
        _processPayment(excess);
    }

    /**
     * @notice Create payment request
     * @param amount Amount requested
     * @param description Description of the payment request
     * @param requestedFrom Address who should fulfill this request
     * @dev Can be called by the client, any recipient, or the contract's manager (its creator)
     */
    function createPaymentRequest(
        uint256 amount,
        string calldata description,
        address requestedFrom
    ) external {
        if (!active) revert ContractInactive();
        // Cheap checks first; the manager lookup is an external call to the factory.
        if (msg.sender != client && !isRecipient[msg.sender] && msg.sender != manager()) revert Unauthorized();
        if (amount == 0) revert InvalidConfiguration();
        if (requestedFrom == address(0)) revert InvalidRecipient();
        
        uint256 requestId = nextRequestId++;
        
        paymentRequests.push(PaymentRequest({
            id: requestId,
            amount: amount,
            description: description,
            createdAt: block.timestamp,
            isPaid: false,
            isCancelled: false,
            createdBy: msg.sender,
            requestedFrom: requestedFrom
        }));
        
        emit PaymentRequestCreated(requestId, amount, description, msg.sender);
    }

    /**
     * @notice Fulfill payment request
     * @param requestId ID of the payment request
     */
    function fulfillPaymentRequest(uint256 requestId) external nonReentrant {
        if (!active) revert ContractInactive();
        
        bool found = false;
        uint256 requestIndex;
        
        for (uint256 i = 0; i < paymentRequests.length; i++) {
            if (paymentRequests[i].id == requestId) {
                found = true;
                requestIndex = i;
                break;
            }
        }
        
        if (!found) revert PaymentRequestNotFound();
        if (paymentRequests[requestIndex].isPaid) revert PaymentRequestAlreadyPaid();
        if (paymentRequests[requestIndex].isCancelled) revert PaymentRequestAlreadyCancelled();
        
        paymentRequests[requestIndex].isPaid = true;
        
        uint256 requestAmount = paymentRequests[requestIndex].amount;
        
        // Transfer tokens from sender
        IERC20(paymentToken).safeTransferFrom(msg.sender, address(this), requestAmount);
        
        // Check if we need to recover creation fee first
        uint256 creationFeeToRecover = 0;
        if (!creationFeeRecovered && creationFee > 0) {
            if (requestAmount >= creationFee) {
                creationFeeToRecover = creationFee;
                creationFeeRecovered = true;
                
                // Transfer creation fee to treasury
                IERC20(paymentToken).safeTransfer(treasury, creationFeeToRecover);
                
                emit CreationFeeRecovered(creationFee);
            }
        }
        
        // Calculate remaining amount after creation fee (if any)
        uint256 remainingAmount = requestAmount - creationFeeToRecover;
        
        // Deduct 1% platform fee from remaining amount
        uint256 platformFee = (remainingAmount * PLATFORM_FEE_BPS) / MAX_BPS;
        IERC20(paymentToken).safeTransfer(treasury, platformFee);
        platformFeesCollected += platformFee;
        
        // Amount to distribute to recipients after fees
        uint256 amountToDistribute = remainingAmount - platformFee;
        
        if (distributionMode == DistributionMode.DIRECT_TRANSFER) {
            // Distribute directly to recipients
            for (uint256 i = 0; i < recipients.length; i++) {
                uint256 recipientAmount = (amountToDistribute * recipients[i].share) / MAX_BPS;
                if (recipientAmount > 0) {
                    IERC20(paymentToken).safeTransfer(recipients[i].addr, recipientAmount);
                    recipients[i].totalReceived += recipientAmount;
                    emit FundsDistributed(recipients[i].addr, recipientAmount);
                }
            }
        } else {
            // Add to claimable balances
            for (uint256 i = 0; i < recipients.length; i++) {
                uint256 recipientAmount = (amountToDistribute * recipients[i].share) / MAX_BPS;
                if (recipientAmount > 0) {
                    recipients[i].pendingBalance += recipientAmount;
                    totalPendingBalance += recipientAmount;
                }
            }
        }
        
        totalDeposited += requestAmount;
        totalDistributed += amountToDistribute;
        
        emit PaymentRequestFulfilled(requestId, msg.sender);
    }

    /**
     * @notice Cancel payment request
     * @param requestId ID of the payment request
     * @dev Only the person from whom payment was requested can cancel
     */
    function cancelPaymentRequest(uint256 requestId) external nonReentrant {
        if (!active) revert ContractInactive();
        
        bool found = false;
        uint256 requestIndex;
        
        for (uint256 i = 0; i < paymentRequests.length; i++) {
            if (paymentRequests[i].id == requestId) {
                found = true;
                requestIndex = i;
                break;
            }
        }
        
        if (!found) revert PaymentRequestNotFound();
        if (paymentRequests[requestIndex].isPaid) revert PaymentRequestAlreadyPaid();
        if (paymentRequests[requestIndex].isCancelled) revert PaymentRequestAlreadyCancelled();
        
        // Can be cancelled by either the client (requestedFrom) OR the recipient who created it (createdBy)
        if (msg.sender != paymentRequests[requestIndex].requestedFrom && 
            msg.sender != paymentRequests[requestIndex].createdBy) {
            revert Unauthorized();
        }
        
        paymentRequests[requestIndex].isCancelled = true;
        
        emit PaymentRequestCancelled(requestId, msg.sender);
    }

    /**
     * @notice Get recipient information
     * @param addr Address of the recipient
     */
    function getRecipientInfo(address addr) external view returns (
        address recipientAddr,
        uint256 share,
        uint256 totalReceived,
        uint256 pendingBalance
    ) {
        if (!isRecipient[addr]) revert InvalidRecipient();
        uint256 idx = recipientIndex[addr];
        Recipient memory r = recipients[idx];
        return (r.addr, r.share, r.totalReceived, r.pendingBalance);
    }

    /**
     * @notice The wallet that created this contract through the factory; it may create payment requests (and, as
     *         their creator, cancel them). Read from the factory's registry, so it needs no extra storage or change
     *         to how the factory initializes clones. address(0) if the factory has no record of this contract.
     */
    function manager() public view returns (address) {
        (, , address creator, , , ) = IPaymentFactoryRegistry(factory).paymentContracts(address(this));
        return creator;
    }

    /// @notice Template version: 2 = manager may create payment requests. (v1 contracts have no `version()`.)
    function version() external pure returns (uint256) {
        return 2;
    }

    /**
     * @notice Get all recipients
     */
    function getRecipients() external view returns (Recipient[] memory) {
        return recipients;
    }

    /**
     * @notice Get contract token balance
     * @return Current balance of payment token held by the contract
     */
    function getContractBalance() external view returns (uint256) {
        return IERC20(paymentToken).balanceOf(address(this));
    }

    /**
     * @notice Get payment request by ID
     * @param requestId ID of the payment request
     */
    function getPaymentRequest(uint256 requestId) external view returns (PaymentRequest memory) {
        for (uint256 i = 0; i < paymentRequests.length; i++) {
            if (paymentRequests[i].id == requestId) {
                return paymentRequests[i];
            }
        }
        revert PaymentRequestNotFound();
    }

    /**
     * @notice Get all payment requests
     */
    function getAllPaymentRequests() external view returns (PaymentRequest[] memory) {
        return paymentRequests;
    }

    /**
     * @notice Update client address
     * @param newClient New client address
     */
    function updateClient(address newClient) external {
        if (msg.sender != client && msg.sender != factory) revert Unauthorized();
        if (newClient == address(0)) revert InvalidRecipient();
        
        address oldClient = client;
        client = newClient;
        
        emit ClientUpdated(oldClient, newClient);
    }

    /**
     * @notice Deactivate contract (emergency stop)
     */
    function deactivate() external {
        if (msg.sender != client && msg.sender != factory) revert Unauthorized();
        active = false;
        emit ContractDeactivated();
    }

    /**
     * @notice Get contract statistics
     */
    function getStats() external view returns (
        uint256 _totalDeposited,
        uint256 _totalDistributed,
        uint256 _platformFeesCollected,
        uint256 _recipientCount,
        bool _active
    ) {
        return (
            totalDeposited,
            totalDistributed,
            platformFeesCollected,
            recipients.length,
            active
        );
    }
}

contracts/payment-factory/templates/SimpleHRDevContract.sol

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

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IPaymentContract.sol";
import "../interfaces/ICreditModule.sol";
import "../TreasuryManager.sol";
import "../MembershipManager.sol";

/**
 * @title SimpleHRDevContract
 * @notice Payment contract for HR-Developer relationships with platform fee
 * @dev Two payment modes:
 *      1. Client pays Developer salary → auto-distributes: 95% Dev, 3% HR, 2% Platform
 *      2. Developer pays commission (when client pays fiat) → distributes: 60% HR, 40% Platform
 * @dev Uses proxy pattern - must be initialized after deployment
 */
contract SimpleHRDevContract is IPaymentContract, ReentrancyGuard {
    using SafeERC20 for IERC20;

    // Contract parameters (no longer immutable for proxy pattern)
    address public client;       // Client who pays salary (optional - if not set, anyone can pay)
    address public hr;
    address public developer;
    address public platformTreasury; // TreasuryManager contract address
    TreasuryManager public treasuryManager;
    address public paymentToken; // address(0) for ETH
    address public creator;      // Who created the contract (Factory)
    address public referrer;     // Referrer who brought the client (gets 0.5%)
    address public partner;      // Partner who promotes developer (gets 12%, pays 3% to platform)
    
    // Reputation Vault - Developer can contribute to vault for reputation score
    address public reputationVault;  // Vault address (set by developer)
    uint256 public reputationFee;    // 0-2000 (0-20%) - developer's choice
    bool public reputationEnabled;   // Whether reputation contribution is active
    
    // Credit Module - For future credit/loan repayments
    address public creditModule;     // Credit module address (optional integration)
    
    // Membership Manager - For subscription refunds and pausing
    MembershipManager public membershipManager;
    bool public refundProcessed;     // Whether membership refund has been processed
    uint256 public totalReceived;    // Total amount received by contract
    
    uint256 public constant HR_FEE = 300;           // 3% to HR
    uint256 public constant PLATFORM_FEE = 200;     // 2% to Platform (or 1.5% if referrer exists)
    uint256 public constant REFERRAL_FEE = 50;      // 0.5% to Referrer
    uint256 public constant PARTNER_FEE = 1200;     // 12% to Partner (gross)
    uint256 public constant PARTNER_PLATFORM_FEE = 300; // 3% Partner pays to Platform
    uint256 public constant PARTNER_NET_FEE = 900;  // 9% Partner keeps (12% - 3%)
    uint256 public constant DEVELOPER_SHARE = 9500; // 95% to Developer (without partner)
    uint256 public constant DEVELOPER_SHARE_WITH_PARTNER = 8300; // 83% to Developer (with partner)
    uint256 public constant MAX_REPUTATION_FEE = 2000; // 20% max
    
    // State variables
    bool public active;
    bool private initialized;                       // Prevent re-initialization
    uint256 private nextPaymentId = 1;

    // Deactivation requires both hr and developer to agree (prevents a single party from
    // unilaterally pausing the contract and then calling emergencyWithdraw alone)
    address public deactivationProposer;
    event DeactivationProposed(address indexed proposer);
    
    // Creation fee recovery
    uint256 public creationFee;                     // Fee to recover from first payment
    bool public creationFeeRecovered = false;       // Whether creation fee has been recovered
    
    enum PaymentMode {
        CLIENT_PAYS,        // Client pays full salary through contract
        DEVELOPER_PAYS      // Developer pays commission (when client pays fiat)
    }
    
    struct PaymentRecord {
        uint256 paymentId;
        uint256 amount;
        address token;
        address payer;
        PaymentMode mode;
        uint256 timestamp;
        bool completed;
    }
    
    enum RequestStatus {
        PENDING,
        APPROVED,
        REJECTED,
        CANCELLED
    }
    
    struct PaymentRequest {
        uint256 requestId;
        uint256 salaryAmount;      // Salary amount that client paid (for reference)
        uint256 commissionAmount;  // Amount developer needs to pay (5% of salary)
        string description;        // Description/invoice details
        address requester;         // HR who created request
        uint256 createdAt;
        RequestStatus status;
        uint256 paidAt;
    }
    
    mapping(uint256 => PaymentRecord) public payments;
    mapping(address => uint256) public pendingBalances;
    mapping(address => uint256) public totalWithdrawn;
    
    // Platform revenue tracking
    uint256 public totalPlatformRevenue;       // Total fees collected by platform
    uint256 public totalHRRevenue;             // Total fees paid to HR
    uint256 public totalPartnerRevenue;        // Total fees paid to partners
    
    uint256 private nextRequestId = 1;
    mapping(uint256 => PaymentRequest) public paymentRequests;
    uint256[] private activeRequestIds;
    mapping(uint256 => uint256) private requestIdToIndex;  // requestId => index in activeRequestIds array
    
    PaymentRecord[] private paymentHistory;
    RecipientInfo[] private recipients;
    
    // Events
    event SalaryPaid(uint256 indexed paymentId, address indexed client, address indexed developer, uint256 amount, PaymentMode mode);
    event CommissionPaid(uint256 indexed paymentId, address indexed developer, uint256 amount);
    event PaymentRequestCreated(uint256 indexed requestId, address indexed hr, uint256 salaryAmount, uint256 commissionAmount, string description);
    event PaymentRequestApproved(uint256 indexed requestId, address indexed developer, uint256 amount);
    event PaymentRequestRejected(uint256 indexed requestId, address indexed developer);
    event PaymentRequestCancelled(uint256 indexed requestId, address indexed hr);
    event ReputationConfigured(address indexed developer, address vault, uint256 feePercent);
    event ReputationContribution(address indexed developer, uint256 amount, uint256 feePercent);
    event CreditModuleSet(address indexed developer, address indexed creditModule);
    event CreditPaymentDeducted(address indexed developer, uint256 amount);
    
    modifier onlyActive() {
        require(active, "Contract is not active");
        _;
    }
    
    modifier onlyHR() {
        require(msg.sender == hr, "Only HR can call this");
        _;
    }
    
    modifier onlyDeveloper() {
        require(msg.sender == developer, "Only Developer can call this");
        _;
    }
    
    modifier onlyParticipants() {
        require(msg.sender == hr || msg.sender == developer, "Not authorized");
        _;
    }

    /// @custom:oz-upgrades-unsafe-allow constructor
    /// @dev Locks the master/implementation contract so initialize() can only ever
    ///      succeed on clones (which get their own fresh storage via delegatecall).
    constructor() {
        initialized = true;
    }

    function initialize(
        address _client,
        address _hr,
        address _developer,
        uint256, // _hrShare - ignored, using fixed 3%
        uint256, // _developerShare - ignored, using fixed 95%
        uint256, // _platformFee - ignored, using fixed 2%
        address _platformTreasury,
        address _paymentToken,
        address _referrer,
        address _partner,
        address _membershipManager
    ) external {
        require(!initialized, "Already initialized");
        require(_hr != address(0), "Invalid HR address");
        require(_developer != address(0), "Invalid developer address");
        require(_platformTreasury != address(0), "Invalid platform treasury");
        // _client can be address(0) - means anyone can pay
        
        initialized = true;
        active = true;
        client = _client;  // Optional - if address(0), anyone can pay
        hr = _hr;
        developer = _developer;
        platformTreasury = _platformTreasury;
        treasuryManager = TreasuryManager(_platformTreasury);
        paymentToken = _paymentToken;
        creator = msg.sender;  // Store who created the contract (Factory)
        referrer = _referrer;  // Store referrer (address(0) if no referrer)
        partner = _partner;    // Store partner (address(0) if no partner)
        
        // Set membership manager for refunds/pausing
        if (_membershipManager != address(0)) {
            membershipManager = MembershipManager(_membershipManager);
        }
        refundProcessed = false;
        totalReceived = 0;
        
        // Initialize nextPaymentId for clones (EIP-1167 doesn't run constructor)
        nextPaymentId = 1;
        
        // Creation fee will be set by Factory after deployment
        creationFee = 0;
        
        // Initialize recipients array with actual percentages
        recipients.push(RecipientInfo({
            recipient: _hr,
            share: HR_FEE,  // 3%
            totalReceived: 0
        }));
        
        recipients.push(RecipientInfo({
            recipient: _developer,
            share: DEVELOPER_SHARE,  // 95%
            totalReceived: 0
        }));
    }

    /**
     * @notice Set creation fee to be recovered from first payment
     * @dev Only creator (Factory) can call this immediately after deployment
     */
    function setCreationFee(uint256 _fee) external {
        require(msg.sender == creator, "Only creator can set creation fee");
        require(!creationFeeRecovered, "Creation fee already set or recovered");
        require(nextPaymentId == 1, "Can only set before first payment");
        creationFee = _fee;
    }

    /**
     * @notice Set membership manager for automatic refunds
     * @dev Only creator (Factory) can call this
     */
    function setMembershipManager(address _membershipManager) external {
        require(msg.sender == creator, "Only creator can set membership manager");
        require(_membershipManager != address(0), "Invalid membership manager");
        membershipManager = MembershipManager(_membershipManager);
    }

    /**
     * @notice Developer sets reputation vault and contribution percentage
     * @param _vault Address of reputation vault (address(0) to disable)
     * @param _feePercent Percentage to contribute (0-2000 = 0-20%)
     */
    function setReputationContribution(address _vault, uint256 _feePercent) external onlyDeveloper {
        require(_feePercent <= MAX_REPUTATION_FEE, "Fee too high (max 20%)");
        
        if (_feePercent > 0) {
            require(_vault != address(0), "Vault address required");
            require(_feePercent >= 100, "Minimum 1% required");
        }
        
        reputationVault = _vault;
        reputationFee = _feePercent;
        reputationEnabled = _feePercent > 0 && _vault != address(0);
        
        emit ReputationConfigured(developer, _vault, _feePercent);
    }

    /**
     * @notice Get reputation configuration
     */
    function getReputationConfig() external view returns (
        address vault,
        uint256 feePercent,
        bool enabled
    ) {
        return (reputationVault, reputationFee, reputationEnabled);
    }

    /**
     * @notice Developer sets credit module for automatic loan repayments
     * @param _creditModule Address of credit module (address(0) to disable)
     */
    function setCreditModule(address _creditModule) external onlyDeveloper {
        creditModule = _creditModule;
        emit CreditModuleSet(developer, _creditModule);
    }

    /**
     * @notice Get credit module address
     */
    function getCreditModule() external view returns (address) {
        return creditModule;
    }


    /**
     * @notice Client pays Developer salary (95% to Dev, 3% to HR, 2% to Platform)
     * @dev If client is set, only client can pay. If client is address(0), anyone can pay.
     */
    function makePayment(uint256 _amount) external payable override onlyActive nonReentrant {
        // If client is set (not address(0)), only client can pay
        if (client != address(0)) {
            require(msg.sender == client, "Only designated client can pay");
        }
        // If client is address(0), anyone can pay (original behavior)
        uint256 paymentAmount;
        if (paymentToken == address(0)) {
            // ETH payment
            paymentAmount = msg.value;
            require(_amount == 0 || _amount == msg.value, "Amount mismatch with ETH sent");
        } else {
            // Token payment
            require(msg.value == 0, "Cannot send ETH for token payment");
            paymentAmount = _amount;
            IERC20(paymentToken).safeTransferFrom(msg.sender, address(this), paymentAmount);
        }
        
        require(paymentAmount > 0, "Payment amount must be greater than 0");
        
        uint256 paymentId = nextPaymentId++;
        
        // Store payment info
        payments[paymentId] = PaymentRecord({
            paymentId: paymentId,
            amount: paymentAmount,
            token: paymentToken,
            payer: msg.sender,
            mode: PaymentMode.CLIENT_PAYS,
            timestamp: block.timestamp,
            completed: false
        });
        
        paymentHistory.push(payments[paymentId]);
        
        // Send creation fee FIRST (if needed)
        uint256 amountToDistribute = paymentAmount;
        if (!creationFeeRecovered && creationFee > 0) {
            uint256 creationFeeToRecover = creationFee;
            if (creationFeeToRecover > paymentAmount) {
                creationFeeToRecover = paymentAmount; // Don't take more than available
            }
            amountToDistribute = paymentAmount - creationFeeToRecover;
            
            if (creationFeeToRecover > 0) {
                if (paymentToken == address(0)) {
                    revert("ETH not supported for creation fee");
                } else {
                    // Direct transfer to treasury (treasury will handle internally)
                    IERC20(paymentToken).safeTransfer(platformTreasury, creationFeeToRecover);
                }
                creationFeeRecovered = true;
            }
        }
        
        // Distribute payment with remaining amount
        _distributeClientPayment(paymentId, amountToDistribute);
        
        emit PaymentReceived(msg.sender, paymentAmount, paymentToken);
        emit SalaryPaid(paymentId, msg.sender, developer, paymentAmount, PaymentMode.CLIENT_PAYS);
    }

    /**
     * @notice Developer pays commission when client paid in fiat (60% to HR, 40% to Platform)
     * @dev Only developer can call this
     */
    function payCommission(uint256 _amount) external payable onlyActive nonReentrant {
        require(msg.sender == developer, "Only developer can pay commission");
        
        uint256 paymentAmount;
        if (paymentToken == address(0)) {
            paymentAmount = msg.value;
            require(_amount == 0 || _amount == msg.value, "Amount mismatch with ETH sent");
        } else {
            require(msg.value == 0, "Cannot send ETH for token payment");
            paymentAmount = _amount;
            IERC20(paymentToken).safeTransferFrom(msg.sender, address(this), paymentAmount);
        }
        
        require(paymentAmount > 0, "Payment amount must be greater than 0");
        
        uint256 paymentId = nextPaymentId++;
        
        // Store payment info
        payments[paymentId] = PaymentRecord({
            paymentId: paymentId,
            amount: paymentAmount,
            token: paymentToken,
            payer: msg.sender,
            mode: PaymentMode.DEVELOPER_PAYS,
            timestamp: block.timestamp,
            completed: false
        });
        
        paymentHistory.push(payments[paymentId]);
        
        // Distribute commission payment
        _distributeDeveloperCommission(paymentId, paymentAmount);
        
        emit PaymentReceived(msg.sender, paymentAmount, paymentToken);
        emit CommissionPaid(paymentId, developer, paymentAmount);
    }

    /**
     * @notice HR creates a payment request for Developer to pay commission
     * @param _salaryAmount Salary amount that client paid to developer in fiat (for reference)
     * @param _description Description of the payment (e.g., "Invoice #123 for Project XYZ")
     */
    function createPaymentRequest(
        uint256 _salaryAmount,
        string memory _description
    ) external onlyHR onlyActive returns (uint256) {
        require(_salaryAmount > 0, "Salary amount must be greater than 0");
        require(bytes(_description).length > 0, "Description required");
        
        // Calculate commission amount based on whether partner exists
        // With partner: 3% HR + 12% Partner + 2% Platform = 17%
        // Without partner: 3% HR + 2% Platform = 5%
        uint256 commissionAmount;
        if (partner != address(0)) {
            commissionAmount = (_salaryAmount * 17) / 100;  // 17% with partner
        } else {
            commissionAmount = (_salaryAmount * 5) / 100;   // 5% without partner
        }
        
        uint256 requestId = nextRequestId++;
        
        paymentRequests[requestId] = PaymentRequest({
            requestId: requestId,
            salaryAmount: _salaryAmount,
            commissionAmount: commissionAmount,
            description: _description,
            requester: msg.sender,
            createdAt: block.timestamp,
            status: RequestStatus.PENDING,
            paidAt: 0
        });
        
        requestIdToIndex[requestId] = activeRequestIds.length;
        activeRequestIds.push(requestId);
        
        emit PaymentRequestCreated(requestId, msg.sender, _salaryAmount, commissionAmount, _description);
        
        return requestId;
    }

    /**
     * @notice Developer approves and pays the commission request
     * @param _requestId ID of the payment request to approve and pay
     */
    function approveAndPayRequest(uint256 _requestId) external payable onlyDeveloper onlyActive nonReentrant {
        PaymentRequest storage request = paymentRequests[_requestId];
        
        require(request.requestId == _requestId, "Request does not exist");
        require(request.status == RequestStatus.PENDING, "Request is not pending");
        require(request.commissionAmount > 0, "Invalid commission amount");
        
        uint256 paymentAmount;
        if (paymentToken == address(0)) {
            paymentAmount = msg.value;
            require(paymentAmount == request.commissionAmount, "Incorrect ETH amount sent");
        } else {
            require(msg.value == 0, "Cannot send ETH for token payment");
            paymentAmount = request.commissionAmount;
            IERC20(paymentToken).safeTransferFrom(msg.sender, address(this), paymentAmount);
        }
        
        // Update request status
        request.status = RequestStatus.APPROVED;
        request.paidAt = block.timestamp;
        
        // Remove from active requests
        _removeFromActiveRequests(_requestId);
        
        // Create payment record
        uint256 paymentId = nextPaymentId++;
        payments[paymentId] = PaymentRecord({
            paymentId: paymentId,
            amount: paymentAmount,
            token: paymentToken,
            payer: msg.sender,
            mode: PaymentMode.DEVELOPER_PAYS,
            timestamp: block.timestamp,
            completed: false
        });
        
        paymentHistory.push(payments[paymentId]);
        
        // Distribute commission payment
        _distributeDeveloperCommission(paymentId, paymentAmount);
        
        emit PaymentReceived(msg.sender, paymentAmount, paymentToken);
        emit PaymentRequestApproved(_requestId, msg.sender, paymentAmount);
        emit CommissionPaid(paymentId, developer, paymentAmount);
    }

    /**
     * @notice Developer rejects a payment request
     * @param _requestId ID of the payment request to reject
     */
    function rejectPaymentRequest(uint256 _requestId) external onlyDeveloper {
        PaymentRequest storage request = paymentRequests[_requestId];
        
        require(request.requestId == _requestId, "Request does not exist");
        require(request.status == RequestStatus.PENDING, "Request is not pending");
        
        request.status = RequestStatus.REJECTED;
        
        // Remove from active requests
        _removeFromActiveRequests(_requestId);
        
        emit PaymentRequestRejected(_requestId, msg.sender);
    }

    /**
     * @notice HR cancels a pending payment request
     * @param _requestId ID of the payment request to cancel
     */
    function cancelPaymentRequest(uint256 _requestId) external onlyHR {
        PaymentRequest storage request = paymentRequests[_requestId];
        
        require(request.requestId == _requestId, "Request does not exist");
        require(request.status == RequestStatus.PENDING, "Request is not pending");
        require(request.requester == msg.sender, "Not the request creator");
        
        request.status = RequestStatus.CANCELLED;
        
        // Remove from active requests
        _removeFromActiveRequests(_requestId);
        
        emit PaymentRequestCancelled(_requestId, msg.sender);
    }

    /**
     * @notice Internal function to remove request from active list (O(1) operation)
     */
    function _removeFromActiveRequests(uint256 _requestId) internal {
        uint256 index = requestIdToIndex[_requestId];
        uint256 lastIndex = activeRequestIds.length - 1;
        
        if (index != lastIndex) {
            uint256 lastRequestId = activeRequestIds[lastIndex];
            activeRequestIds[index] = lastRequestId;
            requestIdToIndex[lastRequestId] = index;
        }
        
        activeRequestIds.pop();
        delete requestIdToIndex[_requestId];
    }

    /**
     * @notice Make token payment (alternative interface)
     */
    function makeTokenPayment(address _token, uint256 _amount) external override {
        require(_token == paymentToken, "Invalid payment token");
        this.makePayment(_amount);
    }

    /**
     * @notice Distribute client payment: 95% Dev, 3% HR, 2% Platform (minus reputation contribution)
     */
    function _distributeClientPayment(uint256 _paymentId, uint256 _totalAmount) internal {
        // Track total received for refund threshold check
        totalReceived += _totalAmount;
        
        // Check if refund should be processed (first time crossing threshold)
        if (!refundProcessed && address(membershipManager) != address(0)) {
            uint256 refundThreshold = membershipManager.refundThreshold();
            if (totalReceived >= refundThreshold) {
                // Process refund for all participants
                address[] memory participants = new address[](partner != address(0) ? 4 : 3);
                uint256 participantCount = 0;
                
                if (client != address(0)) {
                    participants[participantCount++] = client;
                }
                participants[participantCount++] = hr;
                participants[participantCount++] = developer;
                if (partner != address(0)) {
                    participants[participantCount++] = partner;
                }
                
                // Resize array if client is address(0)
                if (client == address(0)) {
                    address[] memory actualParticipants = new address[](participantCount);
                    for (uint256 i = 0; i < participantCount; i++) {
                        actualParticipants[i] = participants[i];
                    }
                    membershipManager.processRefund(actualParticipants, address(this));
                } else {
                    membershipManager.processRefund(participants, address(this));
                }
                
                refundProcessed = true;
                
                // Pause subscriptions for all participants
                for (uint256 i = 0; i < participantCount; i++) {
                    if (participants[i] != address(0)) {
                        membershipManager.pauseSubscription(participants[i], address(this));
                    }
                }
            }
        }
        
        uint256 hrAmount = (_totalAmount * HR_FEE) / 10000;  // 3%
        uint256 platformAmount;
        uint256 referralAmount = 0;
        uint256 partnerGrossAmount = 0;
        uint256 partnerNetAmount = 0;
        uint256 partnerPlatformAmount = 0;
        uint256 devAmount;
        
        // Check if partner exists
        if (partner != address(0)) {
            // Partner mode: 12% to partner (9% net + 3% to platform)
            partnerGrossAmount = (_totalAmount * PARTNER_FEE) / 10000;      // 12%
            partnerPlatformAmount = (_totalAmount * PARTNER_PLATFORM_FEE) / 10000; // 3%
            partnerNetAmount = partnerGrossAmount - partnerPlatformAmount;  // 9%
            
            // Platform gets base fee + partner's 3%
            if (referrer != address(0)) {
                platformAmount = (_totalAmount * (PLATFORM_FEE - REFERRAL_FEE)) / 10000;  // 1.5%
                referralAmount = (_totalAmount * REFERRAL_FEE) / 10000;                    // 0.5%
            } else {
                platformAmount = (_totalAmount * PLATFORM_FEE) / 10000;  // 2%
            }
            platformAmount += partnerPlatformAmount;  // Add partner's 3%
            
            // Developer gets remaining amount (ensures exact balance)
            devAmount = _totalAmount - hrAmount - platformAmount - referralAmount - partnerNetAmount;
        } else {
            // No partner mode: standard distribution
            if (referrer != address(0)) {
                platformAmount = (_totalAmount * (PLATFORM_FEE - REFERRAL_FEE)) / 10000;  // 1.5%
                referralAmount = (_totalAmount * REFERRAL_FEE) / 10000;                    // 0.5%
            } else {
                platformAmount = (_totalAmount * PLATFORM_FEE) / 10000;  // 2%
            }
            
            // Developer gets remaining amount (ensures exact balance)
            devAmount = _totalAmount - hrAmount - platformAmount - referralAmount;
        }
        
        // Calculate reputation contribution from developer's share
        uint256 reputationAmount = 0;
        if (reputationEnabled && reputationFee > 0 && reputationVault != address(0)) {
            reputationAmount = (devAmount * reputationFee) / 10000;
            devAmount -= reputationAmount;
        }
        
        // Calculate credit deduction from developer's share (if credit module is set)
        uint256 creditAmount = 0;
        if (creditModule != address(0)) {
            creditAmount = _applyCreditDeduction(devAmount);
            devAmount -= creditAmount;
        }
        
        // Update pending balances
        pendingBalances[hr] += hrAmount;
        pendingBalances[developer] += devAmount;
        if (partnerNetAmount > 0 && partner != address(0)) {
            pendingBalances[partner] += partnerNetAmount;
        }
        
        // Send platform fee immediately to TreasuryManager
        if (platformAmount > 0) {
            if (paymentToken == address(0)) {
                revert("ETH not supported for platform fee");
            } else {
                IERC20(paymentToken).safeTransfer(platformTreasury, platformAmount);
            }
            totalPlatformRevenue += platformAmount;  // Track platform revenue
            emit PlatformFeeCollected(platformAmount, paymentToken);
        }
        
        // Track HR revenue
        totalHRRevenue += hrAmount;
        
        // Track partner revenue
        if (partnerNetAmount > 0) {
            totalPartnerRevenue += partnerNetAmount;
        }
        
        // Send referral fee if exists
        if (referralAmount > 0 && referrer != address(0)) {
            if (paymentToken == address(0)) {
                (bool success, ) = referrer.call{value: referralAmount}("");
                require(success, "Referral fee transfer failed");
            } else {
                IERC20(paymentToken).safeTransfer(referrer, referralAmount);
            }
            emit PaymentDistributed(referrer, referralAmount, paymentToken);
        }
        
        // Send reputation contribution if enabled
        if (reputationAmount > 0 && reputationVault != address(0)) {
            if (paymentToken == address(0)) {
                (bool success, ) = reputationVault.call{value: reputationAmount}("");
                require(success, "Reputation contribution failed");
            } else {
                IERC20(paymentToken).safeTransfer(reputationVault, reputationAmount);
            }
            emit ReputationContribution(developer, reputationAmount, reputationFee);
        }
        
        // Send credit payment if applicable
        if (creditAmount > 0 && creditModule != address(0)) {
            if (paymentToken == address(0)) {
                (bool success, ) = creditModule.call{value: creditAmount}("");
                require(success, "Credit payment transfer failed");
            } else {
                IERC20(paymentToken).safeTransfer(creditModule, creditAmount);
            }
            emit CreditPaymentDeducted(developer, creditAmount);
        }
        
        // Mark payment as completed
        payments[_paymentId].completed = true;
        
        emit PaymentDistributed(hr, hrAmount, paymentToken);
        emit PaymentDistributed(developer, devAmount, paymentToken);
        if (partnerNetAmount > 0 && partner != address(0)) {
            emit PaymentDistributed(partner, partnerNetAmount, paymentToken);
        }
    }

    /**
     * @notice Distribute developer commission payment (same logic as on-chain)
     * @dev Developer pays: HR 3% + Partner 12% (if exists) + Platform 2%
     * Partner then pays 3% to platform from his 12%, keeping 9% net
     * Platform pays 0.5% to referrer from platform's 2%, keeping 1.5% net
     * Total developer pays: 17% (with partner) or 5% (without)
     */
    function _distributeDeveloperCommission(uint256 _paymentId, uint256 _totalAmount) internal {
        uint256 hrAmount = (_totalAmount * HR_FEE) / 10000;  // 3%
        uint256 platformFeeAmount = (_totalAmount * PLATFORM_FEE) / 10000;  // 2%
        uint256 partnerGrossAmount;
        uint256 partnerPlatformAmount;
        uint256 referralFeeAmount;
        
        // Partner receives 12% from developer
        if (partner != address(0)) {
            partnerGrossAmount = (_totalAmount * PARTNER_FEE) / 10000;  // 12%
            // Partner must pay 3% to platform from his 12%
            partnerPlatformAmount = (_totalAmount * PARTNER_PLATFORM_FEE) / 10000; // 3%
            uint256 partnerNetAmount = partnerGrossAmount - partnerPlatformAmount;  // 9% net
            
            // Add partner's 3% to platform fee
            platformFeeAmount += partnerPlatformAmount;
            
            // Update pending balance for partner (net amount after platform fee)
            pendingBalances[partner] += partnerNetAmount;
            emit PaymentDistributed(partner, partnerNetAmount, paymentToken);
        }
        
        // Pay referrer from platform's share
        if (referrer != address(0)) {
            referralFeeAmount = (_totalAmount * REFERRAL_FEE) / 10000;  // 0.5%
            platformFeeAmount -= referralFeeAmount;  // Platform pays referrer from its 2%
            
            if (paymentToken == address(0)) {
                revert("ETH not supported for referral fee");
            } else {
                IERC20(paymentToken).safeTransfer(referrer, referralFeeAmount);
            }
            emit PaymentDistributed(referrer, referralFeeAmount, paymentToken);
        }
        
        // Update pending balance for HR
        pendingBalances[hr] += hrAmount;
        
        // Send platform fee to TreasuryManager
        if (platformFeeAmount > 0) {
            if (paymentToken == address(0)) {
                revert("ETH not supported for platform fee");
            } else {
                IERC20(paymentToken).safeTransfer(platformTreasury, platformFeeAmount);
            }
            emit PlatformFeeCollected(platformFeeAmount, paymentToken);
        }
        
        // Mark payment as completed
        payments[_paymentId].completed = true;
        
        emit PaymentDistributed(hr, hrAmount, paymentToken);
    }

    /**
     * @notice Apply credit deduction via credit module
     * @param _devAmount Developer's amount before credit deduction
     * @return creditDeduction Amount deducted for credit repayment
     */
    function _applyCreditDeduction(uint256 _devAmount) internal returns (uint256) {
        if (creditModule == address(0)) {
            return 0;
        }
        
        try ICreditModule(creditModule).processPayment(
            developer,
            _devAmount,
            paymentToken
        ) returns (uint256 deduction) {
            // Validate deduction amount
            if (deduction > 0 && deduction <= _devAmount) {
                return deduction;
            }
        } catch {
            // If credit module fails, continue without deduction
            // This prevents payment failure if credit module has issues
        }
        
        return 0;
    }

    /**
     * @notice Distribute specific payment (for manual distribution)
     */
    function distributePayment(uint256 _paymentId) external override {
        require(payments[_paymentId].amount > 0, "Payment does not exist");
        require(!payments[_paymentId].completed, "Payment already distributed");
        
        PaymentRecord memory payment = payments[_paymentId];
        
        if (payment.mode == PaymentMode.CLIENT_PAYS) {
            _distributeClientPayment(_paymentId, payment.amount);
        } else {
            _distributeDeveloperCommission(_paymentId, payment.amount);
        }
    }

    /**
     * @notice Withdraw pending funds
     */
    function withdrawRecipientFunds(address _recipient) external override nonReentrant {
        require(_recipient == hr || _recipient == developer, "Invalid recipient");
        require(msg.sender == _recipient, "Can only withdraw own funds");
        
        uint256 amount = pendingBalances[_recipient];
        require(amount > 0, "No pending funds");
        
        pendingBalances[_recipient] = 0;
        totalWithdrawn[_recipient] += amount;
        
        // Update recipient info
        for (uint256 i = 0; i < recipients.length; i++) {
            if (recipients[i].recipient == _recipient) {
                recipients[i].totalReceived += amount;
                break;
            }
        }
        
        // Transfer funds
        if (paymentToken == address(0)) {
            (bool success, ) = _recipient.call{value: amount}("");
            require(success, "ETH transfer failed");
        } else {
            IERC20(paymentToken).safeTransfer(_recipient, amount);
        }
        
        emit PaymentDistributed(_recipient, amount, paymentToken);
    }

    /**
     * @notice Quick withdraw for caller
     */
    function withdrawMyFunds() external nonReentrant {
        address recipient = msg.sender;
        require(recipient == hr || recipient == developer || (partner != address(0) && recipient == partner), "Not a recipient");
        
        uint256 amount = pendingBalances[recipient];
        require(amount > 0, "No pending funds");
        
        pendingBalances[recipient] = 0;
        totalWithdrawn[recipient] += amount;
        
        // Update recipient info
        for (uint256 i = 0; i < recipients.length; i++) {
            if (recipients[i].recipient == recipient) {
                recipients[i].totalReceived += amount;
                break;
            }
        }
        
        // Transfer funds
        if (paymentToken == address(0)) {
            (bool success, ) = recipient.call{value: amount}("");
            require(success, "ETH transfer failed");
        } else {
            IERC20(paymentToken).safeTransfer(recipient, amount);
        }
        
        emit PaymentDistributed(recipient, amount, paymentToken);
    }

    // View functions
    function getRecipients() external view override returns (RecipientInfo[] memory) {
        return recipients;
    }

    function getPaymentHistory() external view override returns (PaymentInfo[] memory) {
        PaymentInfo[] memory history = new PaymentInfo[](paymentHistory.length);
        for (uint256 i = 0; i < paymentHistory.length; i++) {
            history[i] = PaymentInfo({
                amount: paymentHistory[i].amount,
                token: paymentHistory[i].token,
                payer: paymentHistory[i].payer,
                timestamp: paymentHistory[i].timestamp,
                completed: paymentHistory[i].completed
            });
        }
        return history;
    }

    function getPendingAmount(address _recipient) external view override returns (uint256) {
        return pendingBalances[_recipient];
    }

    function getTotalDistributed() external view override returns (uint256) {
        uint256 total = 0;
        for (uint256 i = 0; i < recipients.length; i++) {
            total += recipients[i].totalReceived;
        }
        return total;
    }

    function getPlatformFee() external pure override returns (uint256) {
        return PLATFORM_FEE;
    }

    function isActive() external view override returns (bool) {
        return active;
    }

    /**
     * @notice Get creation fee info
     */
    function getCreationFeeInfo() external view returns (uint256 fee, bool recovered) {
        return (creationFee, creationFeeRecovered);
    }

    // Payment Request View Functions
    
    /**
     * @notice Get all active payment requests
     */
    function getActivePaymentRequests() external view returns (PaymentRequest[] memory) {
        PaymentRequest[] memory activeRequests = new PaymentRequest[](activeRequestIds.length);
        for (uint256 i = 0; i < activeRequestIds.length; i++) {
            activeRequests[i] = paymentRequests[activeRequestIds[i]];
        }
        return activeRequests;
    }

    /**
     * @notice Get specific payment request by ID
     */
    function getPaymentRequest(uint256 _requestId) external view returns (PaymentRequest memory) {
        require(paymentRequests[_requestId].requestId == _requestId, "Request does not exist");
        return paymentRequests[_requestId];
    }

    /**
     * @notice Get count of active payment requests
     */
    function getActiveRequestCount() external view returns (uint256) {
        return activeRequestIds.length;
    }

    /**
     * @notice Check if there are pending requests for developer
     */
    function hasPendingRequests() external view returns (bool) {
        return activeRequestIds.length > 0;
    }

    // Admin functions (only participants can control)
    /**
     * @notice Reactivate the contract (either party), or propose/confirm deactivation.
     * @dev Deactivating requires BOTH hr and developer to call setActive(false) - the first
     *      call only records a proposal, the second call (from the other participant)
     *      actually deactivates. This prevents one party from unilaterally pausing the
     *      contract to then call emergencyWithdraw alone.
     */
    function setActive(bool _active) external override onlyParticipants {
        if (_active) {
            active = true;
            deactivationProposer = address(0);
            emit ContractStatusChanged(true);
            return;
        }

        if (deactivationProposer == address(0)) {
            deactivationProposer = msg.sender;
            emit DeactivationProposed(msg.sender);
        } else if (deactivationProposer != msg.sender) {
            active = false;
            deactivationProposer = address(0);
            emit ContractStatusChanged(false);
        }
        // If the same participant calls again before the other confirms, it's a no-op.
    }

    /**
     * @notice Emergency withdraw (only if contract is deactivated)
     * @dev Pays out each recipient's exact recorded pendingBalances first (including partner,
     *      whose funds sit in this contract's balance under a pull-payment pattern), then
     *      splits only the genuine excess/unaccounted balance 50/50 between hr and developer.
     */
    function emergencyWithdraw(address _token) external override onlyParticipants {
        require(!active, "Contract must be deactivated for emergency withdrawal");
        
        if (_token == address(0)) {
            // Withdraw ETH
            uint256 balance = address(this).balance;
            if (balance > 0) {
                (uint256 hrAmount, uint256 devAmount, uint256 partnerAmount) = _computeEmergencyPayout(balance);
                if (partnerAmount > 0) {
                    (bool successP, ) = partner.call{value: partnerAmount}("");
                    require(successP, "Emergency partner ETH withdrawal failed");
                }
                (bool success1, ) = hr.call{value: hrAmount}("");
                (bool success2, ) = developer.call{value: devAmount}("");
                require(success1 && success2, "Emergency ETH withdrawal failed");
            }
        } else {
            // Withdraw tokens
            IERC20 token = IERC20(_token);
            uint256 balance = token.balanceOf(address(this));
            if (balance > 0) {
                (uint256 hrAmount, uint256 devAmount, uint256 partnerAmount) = _computeEmergencyPayout(balance);
                if (partnerAmount > 0) {
                    token.safeTransfer(partner, partnerAmount);
                }
                token.safeTransfer(hr, hrAmount);
                token.safeTransfer(developer, devAmount);
            }
        }
    }

    /**
     * @dev Splits `balance` into each recipient's owed pendingBalances plus an even hr/developer
     *      split of any remainder, and zeroes the corresponding pendingBalances entries.
     */
    function _computeEmergencyPayout(uint256 balance)
        internal
        returns (uint256 hrAmount, uint256 devAmount, uint256 partnerAmount)
    {
        uint256 hrOwed = pendingBalances[hr];
        uint256 devOwed = pendingBalances[developer];
        partnerAmount = partner != address(0) ? pendingBalances[partner] : 0;

        uint256 owed = hrOwed + devOwed + partnerAmount;
        require(balance >= owed, "Balance below recorded obligations");
        uint256 remainder = balance - owed;

        hrAmount = hrOwed + remainder / 2;
        devAmount = devOwed + (remainder - remainder / 2);

        pendingBalances[hr] = 0;
        pendingBalances[developer] = 0;
        if (partner != address(0)) {
            pendingBalances[partner] = 0;
        }
    }

    /**
     * @notice Get recipient information (share, total received, available balance)
     * @param _recipient Address to check
     * @return share Recipient's share in basis points (0 for non-recipients)
     * @return received Total amount received by recipient
     * @return availableBalance Pending balance ready to withdraw
     */
    function getRecipientInfo(address _recipient) external view returns (
        uint256 share,
        uint256 received,
        uint256 availableBalance
    ) {
        // Determine share based on role
        if (_recipient == hr) {
            share = HR_FEE; // 300 = 3%
        } else if (_recipient == developer) {
            // Developer share depends on partner
            if (partner != address(0)) {
                share = DEVELOPER_SHARE_WITH_PARTNER; // 8300 = 83%
            } else {
                share = DEVELOPER_SHARE; // 9500 = 95%
            }
        } else if (_recipient == partner && partner != address(0)) {
            share = PARTNER_NET_FEE; // 900 = 9%
        } else {
            share = 0;
        }
        
        // Get total received from recipients array
        uint256 totalReceivedTemp = 0;
        for (uint256 i = 0; i < recipients.length; i++) {
            if (recipients[i].recipient == _recipient) {
                totalReceivedTemp = recipients[i].totalReceived;
                break;
            }
        }
        
        // Add pending amount to total received for display
        availableBalance = pendingBalances[_recipient];
        received = totalReceivedTemp + availableBalance;
        
        return (share, received, availableBalance);
    }

    /**
     * @notice Get contract summary
     */
    function getContractSummary() external view returns (
        address _hr,
        address _developer, 
        uint256 _totalPayments,
        uint256 _totalDistributed,
        uint256 _hrPending,
        uint256 _devPending,
        bool _active
    ) {
        uint256 totalDist = 0;
        for (uint256 i = 0; i < recipients.length; i++) {
            totalDist += recipients[i].totalReceived;
        }
        
        return (
            hr,
            developer,
            paymentHistory.length,
            totalDist,
            pendingBalances[hr],
            pendingBalances[developer],
            active
        );
    }

    /**
     * @notice Get contract statistics including platform revenue
     */
    function getStats() external view returns (
        uint256 _totalPayments,
        uint256 _totalDistributed,
        uint256 _platformRevenue,
        uint256 _hrRevenue,
        uint256 _partnerRevenue,
        bool _active
    ) {
        uint256 totalDist = 0;
        for (uint256 i = 0; i < recipients.length; i++) {
            totalDist += recipients[i].totalReceived;
        }
        
        return (
            paymentHistory.length,
            totalDist,
            totalPlatformRevenue,
            totalHRRevenue,
            totalPartnerRevenue,
            active
        );
    }

    // Receive function for ETH payments (client pays salary)
    receive() external payable {
        if (paymentToken == address(0) && active) {
            uint256 paymentId = nextPaymentId++;
            
            // Store payment info
            payments[paymentId] = PaymentRecord({
                paymentId: paymentId,
                amount: msg.value,
                token: address(0),
                payer: msg.sender,
                mode: PaymentMode.CLIENT_PAYS,
                timestamp: block.timestamp,
                completed: false
            });
            
            paymentHistory.push(payments[paymentId]);
            
            // Distribute payment immediately
            _distributeClientPayment(paymentId, msg.value);
            
            emit PaymentReceived(msg.sender, msg.value, address(0));
            emit SalaryPaid(paymentId, msg.sender, developer, msg.value, PaymentMode.CLIENT_PAYS);
        } else {
            revert("Invalid payment");
        }
    }
}

node_modules/@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        StringsUpgradeable.toHexString(account),
                        " is missing role ",
                        StringsUpgradeable.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

node_modules/@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControlUpgradeable {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

node_modules/@openzeppelin/contracts-upgradeable/interfaces/IERC1967Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)

pragma solidity ^0.8.0;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 *
 * _Available since v4.8.3._
 */
interface IERC1967Upgradeable {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

node_modules/@openzeppelin/contracts-upgradeable/interfaces/draft-IERC1822Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.0;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822ProxiableUpgradeable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

node_modules/@openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)

pragma solidity ^0.8.2;

import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/IERC1967Upgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import {Initializable} from "../utils/Initializable.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 *
 * _Available since v4.1._
 */
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    function __ERC1967Upgrade_init() internal onlyInitializing {
    }

    function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Returns the current implementation address.
     */
    function _getImplementation() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
        StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Perform implementation upgrade
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeTo(address newImplementation) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }

    /**
     * @dev Perform implementation upgrade with additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
        _upgradeTo(newImplementation);
        if (data.length > 0 || forceCall) {
            AddressUpgradeable.functionDelegateCall(newImplementation, data);
        }
    }

    /**
     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
        // Upgrades from old implementations will perform a rollback test. This test requires the new
        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
        // this special case will break upgrade paths from old UUPS implementation to new ones.
        if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
            _setImplementation(newImplementation);
        } else {
            try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
            } catch {
                revert("ERC1967Upgrade: new implementation is not UUPS");
            }
            _upgradeToAndCall(newImplementation, data, forceCall);
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     */
    function _getAdmin() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
        StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {AdminChanged} event.
     */
    function _changeAdmin(address newAdmin) internal {
        emit AdminChanged(_getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
     */
    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function _getBeacon() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
        require(
            AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
            "ERC1967: beacon implementation is not a contract"
        );
        StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
    }

    /**
     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
     *
     * Emits a {BeaconUpgraded} event.
     */
    function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);
        if (data.length > 0 || forceCall) {
            AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

node_modules/@openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.0;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeaconUpgradeable {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.0;

import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * _Available since v4.1._
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
    address private immutable __self = address(this);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        require(address(this) != __self, "Function must be called through delegatecall");
        require(_getImplementation() == __self, "Function must be called through active proxy");
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
        return _IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeTo(address newImplementation) public virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data, true);
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeTo} and {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal override onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

node_modules/@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @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.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _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());
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

node_modules/@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 ReentrancyGuardUpgradeable is Initializable {
    // 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;

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _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;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.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 IERC20Upgradeable {
    /**
     * @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);
}

node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20PermitUpgradeable {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";
import "../extensions/IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20Upgradeable {
    using AddressUpgradeable for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20PermitUpgradeable token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token));
    }
}

node_modules/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

node_modules/@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)

pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

node_modules/@openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlotUpgradeable {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

node_modules/@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = MathUpgradeable.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, MathUpgradeable.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

node_modules/@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

node_modules/@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165Upgradeable {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

node_modules/@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

node_modules/@openzeppelin/contracts-upgradeable/utils/math/SignedMathUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMathUpgradeable {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

node_modules/@openzeppelin/contracts/access/AccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(account),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
}

node_modules/@openzeppelin/contracts/access/IAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

node_modules/@openzeppelin/contracts/proxy/Clones.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/Clones.sol)

pragma solidity ^0.8.0;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 *
 * _Available since v3.4._
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(0, 0x09, 0x37)
        }
        require(instance != address(0), "ERC1167: create failed");
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        require(instance != address(0), "ERC1167: create2 failed");
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

node_modules/@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());
    }
}

node_modules/@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;
    }
}

node_modules/@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);
}

node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

node_modules/@openzeppelin/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

node_modules/@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

node_modules/@openzeppelin/contracts/utils/Strings.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

node_modules/@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": [
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
    "eth-gas-reporter/=node_modules/eth-gas-reporter/",
    "forge-std/=lib/forge-std/src/",
    "hardhat/=node_modules/hardhat/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.