import { BaseClient, registryActions, tokenActions, paymasterFactoryActions, PaymasterABI, superPaymasterActions, paymasterActions, dvtActions, aggregatorActions } from './chunk-ZSSNU3UF.js';
import { parseEther } from 'viem';

var PaymasterOperatorClient = class extends BaseClient {
  superPaymasterAddress;
  tokenAddress;
  ethUsdPriceFeed;
  xpntsFactory;
  constructor(config) {
    super(config);
    this.superPaymasterAddress = config.superPaymasterAddress;
    this.tokenAddress = config.tokenAddress;
    this.ethUsdPriceFeed = config.ethUsdPriceFeedAddress || "0x694AA1769357215DE4FAC081bf1f309aDC325306";
    this.xpntsFactory = config.xpntsFactoryAddress || "0x0000000000000000000000000000000000000000";
  }
  // ========================================
  // 0. 注册与入驻 (One-Stop Registration)
  // ========================================
  /**
   * Register as SuperPaymaster Operator (one-stop API).
   * This method handles all necessary steps:
   * 1. Checks prerequisites (must have ROLE_COMMUNITY)
   * 2. Checks and approves GToken to GTokenStaking
   * 3. Registers ROLE_PAYMASTER_SUPER
   * 4. Optionally deposits collateral to SuperPaymaster
   *
   * @param params Registration parameters
   * @param options Transaction options
   * @returns Transaction hash of role registration
   */
  async registerAsSuperPaymasterOperator(params, options) {
    try {
      const registryAddr = this.requireRegistry();
      const gTokenAddr = this.requireGToken();
      const gTokenStakingAddr = this.requireGTokenStaking();
      const registry = registryActions(registryAddr);
      const gToken = tokenActions();
      const publicClient = this.getStartPublicClient();
      const ROLE_COMMUNITY = await registry(publicClient).ROLE_COMMUNITY();
      const hasCommunity = await registry(publicClient).hasRole({
        user: this.getAddress(),
        roleId: ROLE_COMMUNITY
      });
      if (!hasCommunity) {
        throw new Error("Must have ROLE_COMMUNITY before registering as SuperPaymaster operator");
      }
      const ROLE_PAYMASTER_SUPER = await registry(publicClient).ROLE_PAYMASTER_SUPER();
      const hasSuper = await registry(publicClient).hasRole({
        user: this.getAddress(),
        roleId: ROLE_PAYMASTER_SUPER
      });
      if (hasSuper) {
        if (params?.depositAmount) {
          return this.depositCollateral(params.depositAmount, options);
        }
        throw new Error("Already registered as SuperPaymaster operator");
      }
      const stakeAmount = params?.stakeAmount || parseEther("50");
      const allowance = await gToken(publicClient).allowance({
        token: gTokenAddr,
        owner: this.getAddress(),
        spender: gTokenStakingAddr
      });
      if (allowance < stakeAmount) {
        const approveHash = await gToken(this.client).approve({
          token: gTokenAddr,
          spender: gTokenStakingAddr,
          amount: stakeAmount * 2n,
          // Approve 2x for future use
          account: options?.account
        });
        await publicClient.waitForTransactionReceipt({ hash: approveHash });
      }
      const registerHash = await registry(this.client).registerRoleSelf({
        roleId: ROLE_PAYMASTER_SUPER,
        data: "0x",
        // SuperPaymaster role doesn't need special data
        account: options?.account
      });
      await publicClient.waitForTransactionReceipt({ hash: registerHash });
      if (params?.depositAmount) {
        await this.depositCollateral(params.depositAmount, options);
      }
      return registerHash;
    } catch (error) {
      throw error;
    }
  }
  /**
   * Deploy a new Paymaster V4 and Register as AOA Operator (one-stop API).
   * This method handles:
   * 1. Checks prerequisites (ROLE_COMMUNITY)
   * 2. Predicts new Paymaster address
   * 3. Deploys Paymaster V4 via Factory
   * 4. Registers ROLE_PAYMASTER_AOA with staking
   *
   * @param params Deployment parameters
   * @param options Transaction options
   * @returns Object containing new paymaster address and transaction hashes
   */
  async deployAndRegisterPaymasterV4(params, options) {
    try {
      const registryAddr = this.requireRegistry();
      const gTokenAddr = this.requireGToken();
      const gTokenStakingAddr = this.requireGTokenStaking();
      const factoryAddr = this.requirePaymasterFactory();
      const registry = registryActions(registryAddr);
      const gToken = tokenActions();
      const factory = paymasterFactoryActions(factoryAddr);
      const publicClient = this.getStartPublicClient();
      const account = options?.account || this.client.account || this.getAddress();
      const accountAddr = typeof account === "string" ? account : account.address;
      const ROLE_COMMUNITY = await registry(publicClient).ROLE_COMMUNITY();
      const hasCommunity = await registry(publicClient).hasRole({
        user: accountAddr,
        roleId: ROLE_COMMUNITY
      });
      if (!hasCommunity) {
        throw new Error("Must have ROLE_COMMUNITY before deploying Paymaster V4");
      }
      const existingPaymaster = await factory(publicClient).getPaymaster({ owner: accountAddr });
      let deployHash = "0x0000000000000000000000000000000000000000000000000000000000000000";
      let paymasterAddress;
      if (existingPaymaster && existingPaymaster !== "0x0000000000000000000000000000000000000000") {
        console.log(`    \u2139\uFE0F  Paymaster already deployed at: ${existingPaymaster}`);
        paymasterAddress = existingPaymaster;
      } else {
        console.log("    \u{1F6E0}\uFE0F Deploying Paymaster V4 with args:", {
          entryPoint: this.requireEntryPoint(),
          owner: accountAddr,
          priceFeed: this.ethUsdPriceFeed,
          factory: factoryAddr
        });
        const { encodeFunctionData } = await import('viem');
        const initData = encodeFunctionData({
          abi: PaymasterABI,
          functionName: "initialize",
          args: [
            this.requireEntryPoint(),
            // EntryPoint v0.7
            accountAddr,
            accountAddr,
            // Treasury defaults to owner
            this.ethUsdPriceFeed,
            200n,
            // serviceFeeRate (2%)
            parseEther("0.1"),
            // maxGasCostCap
            3600n
            // priceStalenessThreshold (1 hour)
          ]
        });
        deployHash = await factory(this.client).deployPaymaster({
          version: params?.version,
          initData,
          account
        });
        await publicClient.waitForTransactionReceipt({ hash: deployHash });
        paymasterAddress = await factory(publicClient).getPaymaster({ owner: accountAddr });
      }
      if (!paymasterAddress || paymasterAddress === "0x0000000000000000000000000000000000000000") {
        throw new Error("Failed to retrieve Paymaster address from Factory");
      }
      const ROLE_PAYMASTER_AOA = await registry(publicClient).ROLE_PAYMASTER_AOA();
      const hasAOA = await registry(publicClient).hasRole({
        user: accountAddr,
        roleId: ROLE_PAYMASTER_AOA
      });
      if (hasAOA) {
        return { paymasterAddress, deployHash, registerHash: "0x0000000000000000000000000000000000000000000000000000000000000000" };
      }
      const stakeAmount = params?.stakeAmount || parseEther("30");
      const allowance = await gToken(publicClient).allowance({
        token: gTokenAddr,
        owner: accountAddr,
        spender: gTokenStakingAddr
      });
      if (allowance < stakeAmount) {
        const approveHash = await gToken(this.client).approve({
          token: gTokenAddr,
          spender: gTokenStakingAddr,
          amount: stakeAmount * 2n,
          account
        });
        await publicClient.waitForTransactionReceipt({ hash: approveHash });
      }
      const { encodeAbiParameters, parseAbiParameters } = await import('viem');
      let roleData = "0x";
      if (stakeAmount > 0) {
        roleData = encodeAbiParameters(parseAbiParameters("uint256"), [stakeAmount]);
      }
      const registerHash = await registry(this.client).registerRoleSelf({
        roleId: ROLE_PAYMASTER_AOA,
        data: roleData,
        account
      });
      await publicClient.waitForTransactionReceipt({ hash: registerHash });
      return {
        paymasterAddress,
        deployHash,
        registerHash
      };
    } catch (error) {
      throw error;
    }
  }
  /**
   * Deposit collateral (aPNTs/GToken) to SuperPaymaster.
   * This is a helper method used by registerAsSuperPaymasterOperator.
   */
  async depositCollateral(amount, options) {
    try {
      const pm = superPaymasterActions(this.superPaymasterAddress);
      const publicClient = this.getStartPublicClient();
      const depositToken = await pm(publicClient).APNTS_TOKEN();
      const token = tokenActions();
      const allowance = await token(publicClient).allowance({
        token: depositToken,
        owner: this.getAddress(),
        spender: this.superPaymasterAddress
      });
      if (allowance < amount) {
        const approveHash = await token(this.client).approve({
          token: depositToken,
          spender: this.superPaymasterAddress,
          amount,
          account: options?.account
        });
        await publicClient.waitForTransactionReceipt({ hash: approveHash });
      }
      return pm(this.client).deposit({
        amount,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
  /**
   * Configure operator parameters (Token, Treasury).
   * Exchange rate is now read live from xPNTsToken.exchangeRate() at runtime.
   * If parameters are undefined, existing values are preserved.
   */
  async configureOperator(xPNTsToken, treasury, options) {
    try {
      const sp = superPaymasterActions(this.superPaymasterAddress);
      const publicClient = this.getStartPublicClient();
      const currentConfig = await sp(publicClient).operators({ operator: this.getAddress() });
      const currentToken = currentConfig.xPNTsToken;
      const currentTreasury = currentConfig.treasury;
      return await sp(this.client).configureOperator({
        xPNTsToken: xPNTsToken || currentToken,
        opTreasury: treasury || currentTreasury,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
  async withdrawCollateral(to, amount, options) {
    try {
      const sp = superPaymasterActions(this.superPaymasterAddress);
      return await sp(this.client).withdrawTo({
        to,
        amount,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
  async isOperator(operator) {
    try {
      const sp = superPaymasterActions(this.superPaymasterAddress);
      const config = await sp(this.getStartPublicClient()).operators({ operator });
      return config.isConfigured;
    } catch (error) {
      return false;
    }
  }
  async getOperatorDetails(operator) {
    try {
      const target = operator || this.getAddress();
      const sp = superPaymasterActions(this.superPaymasterAddress);
      return await sp(this.getStartPublicClient()).operators({ operator: target });
    } catch (error) {
      throw error;
    }
  }
  async initiateExit(options) {
    try {
      const sp = superPaymasterActions(this.superPaymasterAddress);
      return await sp(this.client).unlockStake({
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
  async withdrawStake(to, options) {
    try {
      const sp = superPaymasterActions(this.superPaymasterAddress);
      return await sp(this.client).withdrawStake({
        to,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
  // ========================================
  // 3. 支付代币管理 (基于 PaymasterActions)
  // ========================================
  async addGasToken(token, price, options) {
    try {
      const pm = paymasterActions(this.superPaymasterAddress);
      return await pm(this.client).setTokenPrice({
        token,
        price,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
  async getTokenPrice(token) {
    try {
      const pm = paymasterActions(this.superPaymasterAddress);
      return await pm(this.getStartPublicClient()).tokenPrices({ token });
    } catch (error) {
      throw error;
    }
  }
  async setupPaymasterDeposit(params, options) {
    try {
      const pm = paymasterActions(params.paymaster);
      return await pm(this.client).depositFor({
        user: params.user,
        token: params.token,
        amount: params.amount,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
};

// ../operator/dist/ProtocolClient.js
var ProposalState;
(function(ProposalState2) {
  ProposalState2[ProposalState2["Pending"] = 0] = "Pending";
  ProposalState2[ProposalState2["Active"] = 1] = "Active";
  ProposalState2[ProposalState2["Canceled"] = 2] = "Canceled";
  ProposalState2[ProposalState2["Defeated"] = 3] = "Defeated";
  ProposalState2[ProposalState2["Succeeded"] = 4] = "Succeeded";
  ProposalState2[ProposalState2["Queued"] = 5] = "Queued";
  ProposalState2[ProposalState2["Expired"] = 6] = "Expired";
  ProposalState2[ProposalState2["Executed"] = 7] = "Executed";
})(ProposalState || (ProposalState = {}));
var ProtocolClient = class extends BaseClient {
  dvtValidatorAddress;
  blsAggregatorAddress;
  superPaymasterAddress;
  constructor(config) {
    super(config);
    this.dvtValidatorAddress = config.dvtValidatorAddress;
    this.blsAggregatorAddress = config.blsAggregatorAddress;
    this.superPaymasterAddress = config.superPaymasterAddress;
  }
  // ========================================
  // 1. 提案管理 (DVT)
  // ========================================
  /**
   * Create a new proposal
   */
  async createProposal(target, calldata, description, options) {
    try {
      const dvt = dvtActions(this.dvtValidatorAddress)(this.client);
      return await dvt.createSlashProposal({
        operator: target,
        level: 1,
        // Default level
        reason: description,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
  async signProposal(proposalId, signature = "0x", options) {
    try {
      const dvt = dvtActions(this.dvtValidatorAddress)(this.client);
      return await dvt.signSlashProposal({
        proposalId,
        signature,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
  /**
   * Execute a proposal with collected signatures
   */
  async executeWithProof(proposalId, signatures, options) {
    try {
      const proof = "0x";
      const dvt = dvtActions(this.dvtValidatorAddress)(this.client);
      return await dvt.executeSlashWithProof({
        proposalId,
        repUsers: [],
        // Needs real data in production
        newScores: [],
        epoch: 0n,
        proof,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
  // ========================================
  // 2. 验证器管理 / BLS
  // ========================================
  async registerBLSKey(publicKey, options) {
    try {
      if (!this.blsAggregatorAddress) {
        throw new Error("BLS Aggregator address required for this client");
      }
      const agg = aggregatorActions(this.blsAggregatorAddress)(this.client);
      return await agg.registerBLSPublicKey({
        validator: this.getAddress(),
        publicKey,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
  // ========================================
  // 3. 全局参数管理 (Admin)
  // ========================================
  async setProtocolFee(bps, options) {
    try {
      if (!this.superPaymasterAddress) {
        throw new Error("SuperPaymaster address required for this client");
      }
      const sp = superPaymasterActions(this.superPaymasterAddress);
      return await sp(this.client).setProtocolFee({
        newFeeBPS: bps,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
  async setTreasury(treasury, options) {
    try {
      if (!this.superPaymasterAddress) {
        throw new Error("SuperPaymaster address required for this client");
      }
      const sp = superPaymasterActions(this.superPaymasterAddress);
      return await sp(this.client).setTreasury({
        treasury,
        account: options?.account
      });
    } catch (error) {
      throw error;
    }
  }
};

// ../operator/dist/OperatorLifecycle.js
var OperatorLifecycle = class extends PaymasterOperatorClient {
  constructor(config) {
    super(config);
  }
  // ===========================================
  // 1. Setup Phase (Onboarding)
  // ===========================================
  /**
   * Check if the account is ready to become an operator
   * (e.g., has GToken, has ROLE_COMMUNITY, etc.)
   */
  async checkReadiness() {
    const isOp = await this.isOperator(this.getAddress());
    const details = await this.getOperatorDetails();
    const balance = details.aPNTsBalance || 0n;
    return {
      isConfigured: isOp,
      isActive: isOp,
      // Simplification
      balance
    };
  }
  /**
   * One-click Setup: Register + Deposit + Deploy Node
   * Wraps existing registerAsSuperPaymasterOperator or deployAndRegisterPaymasterV4
   */
  async setupNode(params, options) {
    const hashes = [];
    if (params.type === "SUPER") {
      const h = await this.registerAsSuperPaymasterOperator({
        stakeAmount: params.stakeAmount,
        depositAmount: params.depositAmount
      }, options);
      hashes.push(h);
      const factory = await import('./index.node-55LOPHNQ.js').then((m) => m.xPNTsFactoryActions(this.xpntsFactory)(this.getStartPublicClient()));
      const token = await factory.getTokenAddress({ community: this.getAddress() });
      if (token && token !== "0x0000000000000000000000000000000000000000") {
        const hConfig = await this.configureOperator(
          token,
          this.getAddress(),
          // Default treasury to self
          options
        );
        hashes.push(hConfig);
      }
    } else {
      const result = await this.deployAndRegisterPaymasterV4({
        stakeAmount: params.stakeAmount
      }, options);
      hashes.push(result.deployHash);
      hashes.push(result.registerHash);
    }
    return hashes;
  }
  // ===========================================
  // 2. Operational Phase (Config & Funds)
  // ===========================================
  // Inherits: addGasToken, configureOperator, depositCollateral from PaymasterOperatorClient
  async getOperatorStats() {
    return await this.getOperatorDetails();
  }
  // ===========================================
  // 3. Exit Phase (Withdraw & Leave)
  // ===========================================
  /**
   * Start the exit process: Unstake from Registry/SuperPaymaster and Unlock funds
   */
  async initiateExit(options) {
    return await super.initiateExit(options);
  }
  /**
   * Finalize exit: Withdraw all funds (Collateral + Rewards)
   */
  async withdrawAllFunds(to, options) {
    const recipient = to || this.getAddress();
    const hashes = [];
    const stats = await this.checkReadiness();
    if (stats.balance > 0n) {
      const hCol = await this.withdrawCollateral(recipient, stats.balance, options);
      hashes.push(hCol);
    }
    const client = this.getStartPublicClient();
    const registry = registryActions(this.registryAddress);
    const registryWriter = registryActions(this.registryAddress)(this.client);
    const ROLE_PAYMASTER_SUPER = await registry(client).ROLE_PAYMASTER_SUPER();
    const hasRole = await registry(client).hasRole({ user: this.getAddress(), roleId: ROLE_PAYMASTER_SUPER });
    if (hasRole) {
      const hExit = await registryWriter.exitRole({ roleId: ROLE_PAYMASTER_SUPER, account: options?.account });
      hashes.push(hExit);
    }
    return hashes;
  }
  // Helper: Get GToken Balance
  async getTokenBalance() {
    if (!this.tokenAddress)
      return 0n;
    const token = tokenActions()(this.getStartPublicClient());
    return await token.balanceOf({ token: this.tokenAddress, account: this.getAddress() });
  }
};

export { OperatorLifecycle, PaymasterOperatorClient, ProposalState, ProtocolClient };
//# sourceMappingURL=chunk-O3Y7II3B.js.map
//# sourceMappingURL=chunk-O3Y7II3B.js.map