import { useState, useCallback, useEffect } from "react";
function useContractQuery(contract, method, ...args) {
  const [result, setResult] = useState(null);
  const [err, setErr] = useState(void 0);
  const [loading, setLoading] = useState(true);
  const invokeContractFunction = async () => {
    setLoading(true);
    try {
      const response = await contract[method](...args);
      setResult(response);
      setErr(void 0);
    } catch (err2) {
      setErr(err2);
    } finally {
      setLoading(false);
    }
  };
  const onRefetch = useCallback(() => {
    void invokeContractFunction();
  }, [contract, method, args]);
  useEffect(() => {
    if (method && typeof contract[method] === "function") {
      void invokeContractFunction();
    }
  }, [contract, method]);
  return { data: result, error: err, loading, refetch: onRefetch };
}
function useContractLazyQuery(contract, method, optimisticResponse = null) {
  const [result, setResult] = useState(optimisticResponse);
  const [err, setErr] = useState(void 0);
  const [loading, setLoading] = useState(false);
  const invokeContractFunction = async (...args) => {
    setLoading(true);
    try {
      const response = await contract[method](...args);
      setResult(response);
      setErr(void 0);
    } catch (err2) {
      setErr(err2);
    } finally {
      setLoading(false);
    }
  };
  const onFetch = useCallback(
    (...args) => {
      if (method && typeof contract[method] === "function") {
        void invokeContractFunction(...args);
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [contract, method]
  );
  return { data: result, error: err, loading, fetch: onFetch };
}
function useContractMutation(mutationFn, options) {
  const [txResponse, setTxResponse] = useState(null);
  const [txReceipt, setTxReceipt] = useState(null);
  const [err, setErr] = useState(void 0);
  const [loading, setLoading] = useState(false);
  const mutate = useCallback(
    async (...args) => {
      setLoading(true);
      try {
        const response = await mutationFn(...args);
        if (response == null) {
          throw new Error("No response received from contract call");
        }
        setTxResponse(response);
        const receipt = await response.wait(options.txReceiptWaitConfirmations);
        setTxReceipt(receipt);
        setErr(void 0);
        if (options.onSuccess != null) {
          void options.onSuccess(receipt);
        }
      } catch (err2) {
        setErr(err2);
        if (options.onError != null) {
          void options.onError(err2);
        }
      } finally {
        setLoading(false);
      }
    },
    [options, mutationFn]
  );
  return { txResponse, txReceipt, error: err, loading, mutate };
}
export {
  useContractLazyQuery,
  useContractMutation,
  useContractQuery
};
