import { getSuperPaymasterMiddleware } from './chunk-MPOMWT2J.js';
import { createAAStarPublicClient, RegistryABI } from './chunk-ZSSNU3UF.js';
import { parseAbi, createPublicClient, http, hashTypedData, hashMessage, hexToBytes, encodeFunctionData } from 'viem';
import { useState, useEffect, useCallback } from 'react';

var DVT_ABI = parseAbi([
  "function registerValidator(bytes)",
  "function createProposal(address, uint8, string)",
  "function signProposal(uint256, bytes)"
]);
var DVTClient = class {
  static async registerValidator(wallet, dvtAddr, blsPublicKey) {
    return wallet.writeContract({
      address: dvtAddr,
      abi: DVT_ABI,
      functionName: "registerValidator",
      args: [blsPublicKey],
      chain: wallet.chain
    });
  }
};
function useCreditScore({ chain, rpcUrl, registryAddress, userAddress }) {
  const [creditLimit, setCreditLimit] = useState(null);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    if (!registryAddress || !userAddress || !rpcUrl)
      return;
    const fetchCredit = async () => {
      setLoading(true);
      try {
        const client = createAAStarPublicClient(rpcUrl, chain);
        const limit = await client.readContract({
          address: registryAddress,
          abi: RegistryABI,
          functionName: "getCreditLimit",
          args: [userAddress]
        });
        setCreditLimit(limit);
      } catch (e) {
        console.error("Failed to fetch credit limit:", e);
        setCreditLimit(0n);
      } finally {
        setLoading(false);
      }
    };
    fetchCredit();
  }, [chain, rpcUrl, registryAddress, userAddress]);
  return { creditLimit, loading };
}
function useSuperPaymaster(config) {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const generatePaymasterAndData = useCallback(async (userOp) => {
    setIsLoading(true);
    setError(null);
    try {
      const middleware = getSuperPaymasterMiddleware(config);
      const result = await middleware.sponsorUserOperation({ userOperation: userOp });
      return result.paymasterAndData;
    } catch (err) {
      setError(err);
      throw err;
    } finally {
      setIsLoading(false);
    }
  }, [config.paymasterAddress, config.operator, config.verificationGasLimit, config.postOpGasLimit]);
  return { generatePaymasterAndData, isLoading, error };
}
var EXECUTE_ABI = [
  {
    name: "execute",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "dest", type: "address" },
      { name: "value", type: "uint256" },
      { name: "func", type: "bytes" }
    ],
    outputs: []
  }
];
var ENTRYPOINT_ABI = [
  {
    name: "getNonce",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "sender", type: "address" },
      { name: "key", type: "uint192" }
    ],
    outputs: [{ name: "nonce", type: "uint256" }]
  },
  {
    name: "getUserOpHash",
    type: "function",
    stateMutability: "view",
    inputs: [
      {
        name: "packedUserOp",
        type: "tuple",
        components: [
          { name: "sender", type: "address" },
          { name: "nonce", type: "uint256" },
          { name: "initCode", type: "bytes" },
          { name: "callData", type: "bytes" },
          { name: "accountGasLimits", type: "bytes32" },
          { name: "preVerificationGas", type: "uint256" },
          { name: "gasFees", type: "bytes32" },
          { name: "paymasterAndData", type: "bytes" },
          { name: "signature", type: "bytes" }
        ]
      }
    ],
    outputs: [{ type: "bytes32" }]
  }
];
var DEFAULT_ENTRYPOINT = "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
var AirAccountEIP1193Provider = class {
  config;
  client;
  listeners = /* @__PURE__ */ new Map();
  constructor(config) {
    this.config = config;
    this.client = createPublicClient({ transport: http(config.rpcUrl) });
  }
  async request({ method, params }) {
    switch (method) {
      case "eth_chainId":
        return `0x${this.config.chainId.toString(16)}`;
      case "eth_accounts":
      case "eth_requestAccounts":
        return [this.config.accountAddress];
      case "eth_sendTransaction": {
        const tx = params[0];
        return this._sendTransaction(tx);
      }
      case "personal_sign": {
        const [data] = params;
        const hash = hashMessage({ raw: hexToBytes(data) });
        return this.config.signer(hash);
      }
      case "eth_signTypedData_v4": {
        const [, typedDataJson] = params;
        const typedData = JSON.parse(typedDataJson);
        const hash = hashTypedData({
          domain: typedData.domain,
          types: typedData.types,
          primaryType: typedData.primaryType,
          message: typedData.message
        });
        return this.config.signer(hash);
      }
      default:
        return this._forwardToRpc(method, params);
    }
  }
  on(event, listener) {
    if (!this.listeners.has(event))
      this.listeners.set(event, /* @__PURE__ */ new Set());
    this.listeners.get(event).add(listener);
    return this;
  }
  removeListener(event, listener) {
    this.listeners.get(event)?.delete(listener);
    return this;
  }
  // ── Private ──────────────────────────────────────────────────────
  async _sendTransaction(tx) {
    const entryPoint = this.config.entryPoint ?? DEFAULT_ENTRYPOINT;
    const callData = encodeFunctionData({
      abi: EXECUTE_ABI,
      functionName: "execute",
      args: [tx.to, BigInt(tx.value ?? "0x0"), tx.data ?? "0x"]
    });
    const [nonce, feeData] = await Promise.all([
      this.client.readContract({
        address: entryPoint,
        abi: ENTRYPOINT_ABI,
        functionName: "getNonce",
        args: [this.config.accountAddress, 0n]
      }),
      this.client.estimateFeesPerGas()
    ]);
    const maxFeePerGas = feeData.maxFeePerGas ?? 1000000000n;
    const maxPriorityFeePerGas = feeData.maxPriorityFeePerGas ?? 100000000n;
    const verificationGasLimit = 200000n;
    const callGasLimit = BigInt(tx.gas ?? "0x30000");
    const accountGasLimits = `0x${(verificationGasLimit << 128n | callGasLimit).toString(16).padStart(64, "0")}`;
    const gasFees = `0x${(maxPriorityFeePerGas << 128n | maxFeePerGas).toString(16).padStart(64, "0")}`;
    const userOp = {
      sender: this.config.accountAddress,
      nonce,
      initCode: "0x",
      callData,
      accountGasLimits,
      preVerificationGas: 50000n,
      gasFees,
      paymasterAndData: "0x",
      signature: "0x"
    };
    const userOpHash = await this.client.readContract({
      address: entryPoint,
      abi: ENTRYPOINT_ABI,
      functionName: "getUserOpHash",
      args: [userOp]
    });
    userOp.signature = await this.config.signer(userOpHash);
    const resp = await fetch(this.config.bundlerUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: 1,
        method: "eth_sendUserOperation",
        params: [
          {
            sender: userOp.sender,
            nonce: `0x${userOp.nonce.toString(16)}`,
            initCode: userOp.initCode,
            callData: userOp.callData,
            accountGasLimits: userOp.accountGasLimits,
            preVerificationGas: `0x${userOp.preVerificationGas.toString(16)}`,
            gasFees: userOp.gasFees,
            paymasterAndData: userOp.paymasterAndData,
            signature: userOp.signature
          },
          entryPoint
        ]
      })
    });
    const result = await resp.json();
    if (result.error)
      throw new Error(result.error.message);
    return result.result;
  }
  async _forwardToRpc(method, params) {
    const resp = await fetch(this.config.rpcUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params: params ?? [] })
    });
    const result = await resp.json();
    if (result.error)
      throw new Error(result.error.message);
    return result.result;
  }
};

// ../dapp/dist/eip6963.js
var DEFAULT_ICON = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PGNpcmNsZSBjeD0iMjQiIGN5PSIyNCIgcj0iMjQiIGZpbGw9IiMxQTFBMkUiLz48dGV4dCB4PSIxMiIgeT0iMzIiIGZvbnQtc2l6ZT0iMjQiIGZpbGw9IiNGRkYiPkFBPC90ZXh0Pjwvc3ZnPg==";
var AIRACCOUNT_UUID = "d4e5f6a7-b8c9-4d0e-8f2a-3b4c5d6e7f80";
function announceAirAccount(provider, info = {}) {
  const providerDetail = Object.freeze({
    info: Object.freeze({
      uuid: AIRACCOUNT_UUID,
      name: "AirAccount",
      icon: DEFAULT_ICON,
      rdns: "community.aastar.airaccount",
      ...info
    }),
    provider
  });
  const announce = () => {
    window.dispatchEvent(new CustomEvent("eip6963:announceProvider", { detail: providerDetail }));
  };
  announce();
  window.addEventListener("eip6963:requestProvider", announce);
  return () => window.removeEventListener("eip6963:requestProvider", announce);
}
function watchProviders(onProvider) {
  const handler = (event) => {
    onProvider(event.detail);
  };
  window.addEventListener("eip6963:announceProvider", handler);
  window.dispatchEvent(new Event("eip6963:requestProvider"));
  return () => window.removeEventListener("eip6963:announceProvider", handler);
}

export { AirAccountEIP1193Provider, DVTClient, announceAirAccount, useCreditScore, useSuperPaymaster, watchProviders };
//# sourceMappingURL=chunk-6JCYPTSH.js.map
//# sourceMappingURL=chunk-6JCYPTSH.js.map