UNPKG

@cometh/connect-react-hooks

Version:
1,163 lines (1,134 loc) 485 kB
import * as viem from 'viem'; import { Address, Transport, Chain, PublicClient, Hex, Hash, Abi, ContractFunctionName, ContractFunctionArgs, Account, DeriveChain, ContractFunctionParameters, GetChainParameter, GetValue, FormattedTransactionRequest, UnionOmit, SignableMessage } from 'viem'; import * as _cometh_connect_sdk_4337 from '@cometh/connect-sdk-4337'; import { createSafeSmartAccountParameters, ComethSmartAccountClient, ComethSafeSmartAccount, EnrichedOwner, Signer, webAuthnOptions, QRCodeOptions, IsRecoveryActiveParams, IsRecoveryActiveReturnType, RecoveryParamsResponse, GetRecoveryRequestParams, CancelRecoveryRequestParams, GrantPermissionParameters, GrantPermissionResponse, UsePermissionParameters, SafeSigner } from '@cometh/connect-sdk-4337'; import { z, A, O, aQ, a8, aA, b } from './hydration-HsNFcW1O.js'; import React, { ReactNode } from 'react'; import { GetAccountParameter } from 'viem/_types/types/account'; import { Prettify } from 'viem/chains'; import { UnionEvaluate } from 'viem/types/utils'; import { UseQueryParameters } from 'wagmi/query'; import { EstimateUserOperationGasParameters, EstimateUserOperationGasReturnType } from 'viem/account-abstraction'; import * as permissionless_actions_smartAccount from 'permissionless/actions/smartAccount'; import * as viem__types_account_abstraction from 'viem/_types/account-abstraction'; import * as viem__types_actions_siwe_verifySiweMessage from 'viem/_types/actions/siwe/verifySiweMessage'; import * as viem_experimental from 'viem/experimental'; import * as viem_actions from 'viem/actions'; import * as viem__types_utils_ccip from 'viem/_types/utils/ccip'; type ConnectParameters = { address?: Address; passKeyName?: string; }; declare const useConnect: () => { connect: (params?: ConnectParameters) => void; connectAsync: (params?: ConnectParameters) => Promise<void>; isPending: boolean; error: Error | null; }; interface UseBaseQueryOptions<TQueryFnData = unknown, TError = z, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends A = A> extends a8<TQueryFnData, TError, TData, TQueryData, TQueryKey> { /** * Set this to `false` to unsubscribe this observer from updates to the query cache. * Defaults to `true`. */ subscribed?: boolean; } interface UseQueryOptions<TQueryFnData = unknown, TError = z, TData = TQueryFnData, TQueryKey extends A = A> extends O<UseBaseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>, 'suspense'> { } type UseBaseQueryResult<TData = unknown, TError = z> = aA<TData, TError>; type UseQueryResult<TData = unknown, TError = z> = UseBaseQueryResult<TData, TError>; interface UseMutationOptions<TData = unknown, TError = z, TVariables = void, TContext = unknown> extends O<aQ<TData, TError, TVariables, TContext>, '_defaulted'> { } type NetworkParams = { chain?: Chain; bundlerUrl?: string; paymasterUrl?: string; publicClient?: PublicClient; }; type OmitConfig<T> = Omit<T, "chain" | "paymasterUrl" | "bundlerUrl" | "publicClient"> & { networksConfig: NetworkParams[]; }; type ConnectConfig = OmitConfig<createSafeSmartAccountParameters>; type ContextComethSmartAccountClient = ComethSmartAccountClient<Transport, Chain, ComethSafeSmartAccount>; declare const ConnectProvider: <TConfig extends ConnectConfig, TQueryClient extends b | undefined>({ children, config, queryClient, }: { children: ReactNode; config: TConfig; queryClient: TQueryClient; }) => React.JSX.Element; type AccountStatus = "connected" | "disconnected"; interface UseAccountResult { address: Address | undefined; smartAccountClient: ContextComethSmartAccountClient | null; isConnected: boolean; isDisconnected: boolean; status: AccountStatus; chain: Chain | undefined; chainId: number | undefined; } declare const useAccount: () => UseAccountResult; type MutationOptionsWithoutMutationFn = Omit<UseMutationOptions<any, any, any, any>, "mutationFn" | "mutationKey">; type Transaction = { to: Address; value: bigint; data: Hex; }; type QueryResultType<T> = { data?: T; error: unknown; isPending: boolean; isSuccess: boolean; isError: boolean; }; /** * Props for the useSendTransaction hook. * @property {Transaction | Transaction[]} transactions - A single transaction or an array of transactions to send. */ type UseSendTransactionProps = { calls: Transaction | Transaction[]; }; /** * Type for the sendTransaction function. * This function doesn't return a promise, suitable for fire-and-forget usage. */ type SendTransactionMutate = (variables: UseSendTransactionProps) => void; /** * Type for the sendTransactionAsync function. * This function returns a promise that resolves to the transaction hash. */ type SendTransactionMutateAsync = (variables: UseSendTransactionProps) => Promise<Hash>; type UseSendTransactionReturn = QueryResultType<Hash> & { sendTransaction: SendTransactionMutate; sendTransactionAsync: SendTransactionMutateAsync; }; /** * A custom hook for sending transactions through a smart account. * * This hook provides functionality to send either a single transaction or multiple transactions * in batch. It uses the smart account client to process and send these transactions. * * @param mutationProps Optional mutation properties from @tanstack/react-query * * @example * ```tsx * import { useSendTransaction } from "@/hooks/useSendTransaction"; * import { useState } from "react"; * import { parseEther, Address } from "viem"; * * export const TransactionSender = () => { * const { sendTransaction, sendTransactionAsync, isLoading, isError, error, isSuccess, data } = useSendTransaction(); * const [recipient, setRecipient] = useState<Address>(); * const [amount, setAmount] = useState<string>("0"); * * const handleSendTransaction = () => { * if (recipient) { * sendTransaction({ * to: recipient, * value: parseEther(amount), * data: "0x", * }); * } * }; * * const handleSendBatchTransactions = async () => { * if (recipient) { * try { * const hash = await sendTransactionAsync({ * calls: [ * { * to: recipient, * value: parseEther(amount), * data: "0x", * }, * { * to: recipient, * value: parseEther((Number(amount) * 2).toString()), * data: "0x", * } * ] * }); * console.log("Batch transactions sent! Hash:", hash); * } catch (error) { * console.error("Error sending batch transactions:", error); * } * } * }; * * return ( * <div> * <input * placeholder="Recipient address" * onChange={(e) => setRecipient(e.target.value as Address)} * /> * <input * type="number" * placeholder="Amount in ETH" * onChange={(e) => setAmount(e.target.value)} * /> * <button onClick={handleSendTransaction} disabled={isLoading}> * Send Transaction * </button> * <button onClick={handleSendBatchTransactions} disabled={isLoading}> * Send Batch Transactions * </button> * {isError && <p>Error: {error.message}</p>} * {isSuccess && <p>Transaction sent! Hash: {data}</p>} * </div> * ); * }; * ``` * * @returns An object containing: * - All properties from the mutation object (`isLoading`, `isError`, `error`, `isSuccess`, `data`, etc.) * - `sendTransaction`: A function to trigger the transaction sending without waiting for the result. * - `sendTransactionAsync`: A function to trigger the transaction sending and wait for the result. */ declare const useSendTransaction: (mutationProps?: MutationOptionsWithoutMutationFn) => UseSendTransactionReturn; /** * @description A custom hook for writing to smart contracts through a smart account. * * This hook provides functionality to write to a smart contract by encoding the function call * and sending it as a transaction. It uses the smart account client to process and send these transactions. * * @param mutationProps Optional mutation properties from @tanstack/react-query * * @example * ```tsx * import { useWriteContract } from "@/hooks/useWriteContract"; * import { useState } from "react"; * import { parseEther, Address } from "viem"; * import { abi } from './contractABI'; * * export const ContractWriter = () => { * const { writeContract, isLoading, isError, error, isSuccess, data } = useWriteContract(); * const [recipient, setRecipient] = useState<Address>(); * const [amount, setAmount] = useState<string>("0"); * * const handleWriteContract = async () => { * if (recipient) { * try { * const hash = await writeContract({ * abi, * address: '0xYourContractAddress', * functionName: 'transfer', * args: [recipient, parseEther(amount)], * }); * console.log("Contract write successful! Hash:", hash); * } catch (error) { * console.error("Error writing to contract:", error); * } * } * }; * * return ( * <div> * <input * placeholder="Recipient address" * onChange={(e) => setRecipient(e.target.value as Address)} * /> * <input * type="number" * placeholder="Amount in ETH" * onChange={(e) => setAmount(e.target.value)} * /> * <button onClick={handleWriteContract} disabled={isLoading}> * Write to Contract * </button> * {isError && <p>Error: {error.message}</p>} * {isSuccess && <p>Contract write successful! Hash: {data}</p>} * </div> * ); * }; * ``` * * @returns An object containing: * - All properties from the mutation object (`isLoading`, `isError`, `error`, `isSuccess`, `data`, etc.) * - `writeContract`: A function to trigger the contract write, which returns a promise * that resolves to the transaction hash. */ /** * Type for the writeContract function. * This function doesn't return a promise, suitable for fire-and-forget usage. */ type WriteContractMutate = (variables: WriteContractParameters) => void; /** * Type for the writeContractAsync function. * This function returns a promise that resolves to the transaction hash. */ type WriteContractMutateAsync = (variables: WriteContractParameters) => Promise<Hash>; type UseWriteContractReturn = QueryResultType<Hash> & { writeContract: WriteContractMutate; writeContractAsync: WriteContractMutateAsync; }; type WriteContractParameters<abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName<abi, "nonpayable" | "payable"> = ContractFunctionName<abi, "nonpayable" | "payable">, args extends ContractFunctionArgs<abi, "nonpayable" | "payable", functionName> = ContractFunctionArgs<abi, "nonpayable" | "payable", functionName>, chain extends Chain | undefined = Chain | undefined, account extends Account | undefined = Account | undefined, chainOverride extends Chain | undefined = Chain | undefined, derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>> = ContractFunctionParameters<abi, "nonpayable" | "payable", functionName, args> & GetChainParameter<chain, chainOverride> & Prettify<GetAccountParameter<account> & GetValue<abi, functionName, FormattedTransactionRequest<derivedChain>["value"]> & { /** Data to append to the end of the calldata. Useful for adding a ["domain" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */ dataSuffix?: Hex; }> & UnionEvaluate<UnionOmit<FormattedTransactionRequest<derivedChain>, "data" | "from" | "to" | "value">>; declare const useWriteContract: (mutationProps?: MutationOptionsWithoutMutationFn) => UseWriteContractReturn; declare const useDisconnect: () => { disconnect: () => void; disconnectAsync: () => Promise<void>; isPending: boolean; error: Error | null; }; type AddOwnerParameters = { ownerToAdd: Address; }; type RemoveOwnerParameters = { ownerToRemove: Address; }; type UseAddOwnerReturn = QueryResultType<Hash> & { addOwner: (params: AddOwnerParameters) => void; addOwnerAsync: (params: AddOwnerParameters) => Promise<Hash>; }; type UseRemoveOwnerReturn = QueryResultType<Hash> & { removeOwner: (params: RemoveOwnerParameters) => void; removeOwnerAsync: (params: RemoveOwnerParameters) => Promise<Hash>; }; /** * A custom hook for adding a new owner to a smart account. * @param mutationProps Optional mutation properties from @tanstack/react-query * @returns An object containing the mutation function and related properties. * @throws {Error} If no smart account is found when trying to add an owner. */ declare const useAddOwner: (mutationProps?: Omit<UseMutationOptions<Hash, Error, AddOwnerParameters>, "mutationFn">) => UseAddOwnerReturn; /** * A custom hook for removing an owner from a smart account. * @param mutationProps Optional mutation properties from @tanstack/react-query * @returns An object containing the mutation function and related properties. * @throws {Error} If no smart account is found when trying to remove an owner. */ declare const useRemoveOwner: (mutationProps?: Omit<UseMutationOptions<Hash, Error, RemoveOwnerParameters>, "mutationFn">) => UseRemoveOwnerReturn; /** * A custom hook for retrieving the list of current owners of a smart account. * @param queryProps Optional query properties from @tanstack/react-query * @returns An object containing the query result and related properties. * @throws {Error} If no smart account is found when trying to get owners. */ declare const useGetOwners: (queryProps?: Omit<UseQueryOptions<readonly Address[], Error>, "queryKey" | "queryFn">) => UseQueryResult<readonly `0x${string}`[], Error>; /** * A custom hook for retrieving detailed information about current owners of a smart account. * @param queryProps Optional query properties from @tanstack/react-query * @returns An object containing the query result and related properties. * @throws {Error} If no smart account is found when trying to get enriched owners. */ declare const useGetEnrichedOwners: (queryProps?: Omit<UseQueryOptions<EnrichedOwner[], Error>, "queryKey" | "queryFn">) => UseQueryResult<EnrichedOwner[], Error>; /** * Props for the useValidateAddDevice hook. * @property {Signer} signer - The signer to be added as a new device. */ type UseValidateAddDeviceProps = { signer: Signer; }; /** * Type for the validateAddDevice function. * This function doesn't return a promise, suitable for fire-and-forget usage. */ type ValidateAddDeviceMutate = (variables: UseValidateAddDeviceProps) => void; /** * Type for the validateAddDeviceAsync function. * This function returns a promise that resolves to the transaction hash. */ type ValidateAddDeviceMutateAsync = (variables: UseValidateAddDeviceProps) => Promise<Hash>; type UseValidateAddDeviceReturn = QueryResultType<Hash> & { validateAddDevice: ValidateAddDeviceMutate; validateAddDeviceAsync: ValidateAddDeviceMutateAsync; }; /** * A hook that validates the adding of a new device as passkey owner of the smart account. * * This hook uses the `validateAddDevice` method from the smart account client to add a new signer * to the user's account. It's typically used in the process of adding a new device or recovery method * to a user's account. * * @param mutationProps Optional mutation properties from @tanstack/react-query * * @returns An object containing: * - All properties from the mutation object (`isPending`, `isError`, `error`, `isSuccess`, `data`, etc.) * - `validateAddDevice`: A function to trigger the device validation without waiting for the result. * - `validateAddDeviceAsync`: A function to trigger the device validation and wait for the result. * * @throws {Error} If no smart account is found when trying to validate adding a device. */ declare const useValidateAddDevice: (mutationProps?: MutationOptionsWithoutMutationFn) => UseValidateAddDeviceReturn; /** * Props for the useVerifyMessage hook. * @property {string} message - The message to verify. * @property {Hex} signature - The signature to verify. */ type UseVerifySignatureProps = { message: string; signature: Hex; }; /** * Type for the verifyMessage function. * This function doesn't return a promise, suitable for fire-and-forget usage. */ type VerifyMessageMutate = (variables: UseVerifySignatureProps) => void; /** * Type for the verifyMessageAsync function. * This function returns a promise that resolves to a boolean indicating if the signature is valid. */ type VerifyMessageMutateAsync = (variables: UseVerifySignatureProps) => Promise<boolean>; type UseVerifyMessageReturn = { data?: boolean; error: unknown; isPending: boolean; isSuccess: boolean; isError: boolean; verifyMessage: VerifyMessageMutate; verifyMessageAsync: VerifyMessageMutateAsync; }; /** * A hook that verifies a message signature for the current smart account. * * This hook uses the `verifySignature` method from the smart account client to verify * if a given signature is valid for a specific message. It's typically used to authenticate * user actions or verify the integrity of signed messages. * * @param mutationProps Optional mutation properties from @tanstack/react-query * * @returns An object containing: * - All properties from the mutation object (`isPending`, `isError`, `error`, `isSuccess`, `data`, etc.) * - `verifyMessage`: A function to trigger the signature verification without waiting for the result. * - `verifyMessageAsync`: A function to trigger the signature verification and wait for the result. * * @throws {Error} If no smart account is found when trying to verify a signature. */ declare const useVerifyMessage: (mutationProps?: MutationOptionsWithoutMutationFn) => UseVerifyMessageReturn; type GasPriceResult = { maxFeePerGas: bigint; maxPriorityFeePerGas: bigint; }; /** * @description A hook that fetches the current gas price for transactions on the connected blockchain. * * This hook uses a public client to estimate the current gas fees. It returns both the `maxFeePerGas` * and `maxPriorityFeePerGas`. The `maxFeePerGas` is doubled to provide a buffer for potential gas price fluctuations. * * @param rpcUrl Optional RPC URL to use for the public client. If not provided, it will use the default RPC URL. * @param queryProps Optional query properties from @tanstack/react-query * * @example * ```tsx * import { useGetGasPrice } from "@/hooks/useGetGasPrice"; * import { formatEther } from "viem"; * * export const GasPriceDisplay = () => { * const { data: gasPrice, isLoading, error } = useGetGasPrice(); * * if (isLoading) return <p>Loading gas prices...</p>; * if (error) return <p>Error fetching gas prices: {error.message}</p>; * * return ( * <div> * <h2>Current Gas Prices</h2> * <p>Max Fee Per Gas: {formatEther(gasPrice.maxFeePerGas)} ETH</p> * <p>Max Priority Fee Per Gas: {formatEther(gasPrice.maxPriorityFeePerGas)} ETH</p> * </div> * ); * }; * ``` * * @returns An object containing the query result and related properties. */ declare const useGetGasPrice: (rpcUrl?: string, queryProps?: Omit<UseQueryOptions<GasPriceResult, Error>, "queryKey" | "queryFn">) => UseQueryResult<GasPriceResult, Error>; type UseRetrieveAccountAddressFromPasskeyOptions = { apiKey: string; chain: Chain; fullDomainSelected?: boolean; baseUrl?: string; queryProps?: UseQueryParameters; }; declare const useRetrieveAccountAddressFromPasskeys: ({ apiKey, chain, fullDomainSelected, baseUrl, }: UseRetrieveAccountAddressFromPasskeyOptions) => { retrieveAddress: () => Promise<`0x${string}`>; isPending: boolean; error: Error | null; }; declare const useRetrieveAccountAddressFromPasskeyId: ({ apiKey, chain, fullDomainSelected, baseUrl, }: UseRetrieveAccountAddressFromPasskeyOptions) => { retrieveAddress: (id: string) => Promise<`0x${string}`>; isPending: boolean; error: Error | null; }; type CreateNewSignerParameters = { passKeyName?: string; webAuthnOptions?: webAuthnOptions; fullDomainSelected?: boolean; }; type SerializeUrlParameters = { validationPageUrl: string; signerPayload: Signer; }; type GenerateQRCodeUrlParameters = { validationPageUrl: string; signerPayload: Signer; options?: QRCodeOptions; }; /** * Hook for creating a new signer * * @param apiKey - The API key for authentication * @param mutationProps - Optional mutation properties from @tanstack/react-query * * @example * ```tsx * import { useCreateNewSigner } from './path-to-this-file'; * * const MyComponent = () => { * const { createSigner, isLoading, error, data } = useCreateNewSigner('your-api-key'); * * const handleCreateSigner = async () => { * try { * const newSigner = await createSigner({ * passKeyName: 'MyNewPasskey' * }); * console.log('New signer created:', newSigner); * } catch (err) { * console.error('Error creating signer:', err); * } * }; * * return ( * <div> * <button onClick={handleCreateSigner} disabled={isLoading}> * Create New Signer * </button> * {isLoading && <p>Creating signer...</p>} * {error && <p>Error: {error.message}</p>} * {data && <p>Signer created successfully!</p>} * </div> * ); * }; * ``` * * @returns An object containing the mutation function and related properties. */ declare const useCreateNewSigner: (apiKey: string, baseUrl?: string) => { createSigner: (params?: CreateNewSignerParameters) => void; createSignerAsync: (params?: CreateNewSignerParameters) => Promise<Signer>; isPending: boolean; error: Error | null; }; declare const useSerializeUrlWithSignerPayload: () => { serializeUrl: (params: SerializeUrlParameters) => void; serializeUrlAsync: (params: SerializeUrlParameters) => Promise<URL>; isPending: boolean; error: Error | null; }; declare const useGenerateQRCodeUrl: () => { generateQRCode: (params: GenerateQRCodeUrlParameters) => void; generateQRCodeAsync: (params: GenerateQRCodeUrlParameters) => Promise<string>; isPending: boolean; error: Error | null; }; type SignMessageArgs = { message: SignableMessage; }; type SignMessageMutate = (variables: SignMessageArgs) => void; type SignMessageMutateAsync = (variables: SignMessageArgs) => Promise<Hex>; type UseSignMessageReturn = QueryResultType<Hash> & { signMessage: SignMessageMutate; signMessageAsync: SignMessageMutateAsync; }; declare function useSignMessage(): UseSignMessageReturn; type UseSetUpRecoveryModuleReturn = QueryResultType<Hash> & { setUpRecoveryModule: () => void; setUpRecoveryModuleAsync: () => Promise<Hash>; }; /** * A custom hook for setting up a recovery module for a smart account. * * This hook provides functionality to set up a recovery module, which includes * deploying a delay module and enabling necessary modules for the smart account. * It uses the smart account client to process and send the required transactions. * * @template entryPoint - The type of EntryPoint used in the smart account setup. * * @example * ```tsx * import { useSetUpRecoveryModule } from "@/hooks/useSetUpRecoveryModule"; * * export const RecoverySetup = () => { * const { * setUpRecoveryModule, * setUpRecoveryModuleAsync, * isLoading, * isError, * error, * isSuccess, * data * } = useSetUpRecoveryModule(); * * const handleSetUp = async () => { * try { * const result = await setUpRecoveryModuleAsync(); * console.log('Recovery module set up successfully:', result); * } catch (error) { * console.error('Error setting up recovery module:', error); * } * }; * * return ( * <div> * <button onClick={handleSetUp} disabled={isLoading}> * Set Up Recovery Module * </button> * {isLoading && <p>Setting up recovery module...</p>} * {isError && <p>Error: {error?.message}</p>} * {isSuccess && <p>Recovery module set up successfully. Hash: {data}</p>} * </div> * ); * }; * ``` * * @returns An object containing: * - `setUpRecoveryModule`: A function to trigger the recovery module setup without waiting for the result. * - `setUpRecoveryModuleAsync`: A function to trigger the recovery module setup and wait for the result. * - `isLoading`: A boolean indicating if the setup is in progress. * - `isError`: A boolean indicating if an error occurred during setup. * - `error`: The error object if an error occurred, null otherwise. * - `isSuccess`: A boolean indicating if the setup was successful. * - `data`: The transaction hash (Hex) returned after successful setup. */ declare function useSetUpRecovery(): UseSetUpRecoveryModuleReturn; type UseIsRecoveryActiveProps = IsRecoveryActiveParams; type UseIsRecoveryActiveReturn = { data: IsRecoveryActiveReturnType | undefined; isLoading: boolean; isError: boolean; error: Error | null; }; /** * A custom hook for checking if recovery is active for a smart account. * * This hook provides functionality to check if a delay module is deployed * and retrieve the guardian address for the smart account's recovery setup. * * @param {UseIsRecoveryActiveProps} props - The properties for the hook. * @param {string} [props.publicClient] - Optional client for the blockchain network. * * @example * ```tsx * import { useIsRecoveryActive } from "@/hooks/useIsRecoveryActive"; * * export const RecoveryStatus = () => { * const { data, isLoading, isError, error } = useIsRecoveryActive(); * * if (isLoading) return <p>Loading recovery status...</p>; * if (isError) return <p>Error: {error?.message}</p>; * * return ( * <div> * <p>Recovery Module Deployed: {data?.isDelayModuleDeployed ? 'Yes' : 'No'}</p> * <p>Guardian Address: {data?.guardianAddress || 'Not set'}</p> * </div> * ); * }; * ``` * * @returns An object containing: * - `data`: The result of the recovery status check, or undefined if not yet loaded. * - `isLoading`: A boolean indicating if the check is in progress. * - `isError`: A boolean indicating if an error occurred during the check. * - `error`: The error object if an error occurred, null otherwise. */ declare function useIsRecoveryActive(props?: UseIsRecoveryActiveProps): UseIsRecoveryActiveReturn; type UseGetRecoveryRequestProps = GetRecoveryRequestParams; type UseGetRecoveryRequestReturn = { data: RecoveryParamsResponse | undefined; isLoading: boolean; isError: boolean; error: Error | null; }; /** * A custom hook for getting the recovery request for a smart account. * * This hook provides functionality to check if a recovery request is active * and retrieve the details of the recovery request if one exists. * * @param {UseGetRecoveryRequestProps} props - The properties for the hook. * @param {string} [props.publicClient] - Optional client for the blockchain network. * @param {UseQueryOptions} [queryOptions] - Optional configuration for the React Query hook. * * @example * ```tsx * import { useGetRecoveryRequest } from "@/hooks/useGetRecoveryRequest"; * * export const RecoveryRequestStatus = () => { * const { data, isLoading, isError, error } = useGetRecoveryRequest(); * * if (isLoading) return <p>Loading recovery request status...</p>; * if (isError) return <p>Error: {error?.message}</p>; * * return ( * <div> * {data ? ( * <> * <p>Recovery Request Active</p> * <p>New Owner: {data.newOwner}</p> * <p>Execution Time: {new Date(data.executionTime * 1000).toLocaleString()}</p> * </> * ) : ( * <p>No active recovery request</p> * )} * </div> * ); * }; * ``` * * @returns An object containing: * - `data`: The recovery request details, or undefined if no request is active or not yet loaded. * - `isLoading`: A boolean indicating if the check is in progress. * - `isError`: A boolean indicating if an error occurred during the check. * - `error`: The error object if an error occurred, null otherwise. * - `refetch`: A function to manually trigger a refetch of the recovery request status. */ declare function useGetRecoveryRequest(props?: UseGetRecoveryRequestProps, queryOptions?: Omit<UseQueryOptions<RecoveryParamsResponse | undefined, Error>, "queryKey" | "queryFn">): UseGetRecoveryRequestReturn; type UseCancelRecoveryRequestProps = CancelRecoveryRequestParams; type CancelRecoveryRequestMutate = (variables: UseCancelRecoveryRequestProps) => void; type CancelRecoveryRequestMutateAsync = (variables: UseCancelRecoveryRequestProps) => Promise<Hex>; type UseCancelRecoveryRequestReturn = QueryResultType<Hash> & { cancelRecoveryRequest: CancelRecoveryRequestMutate; cancelRecoveryRequestAsync: CancelRecoveryRequestMutateAsync; }; /** * A custom hook for canceling a recovery request for a smart account. * * This hook provides functionality to cancel an active recovery request * for a smart account. It uses the smart account client to process and send * the required transaction to cancel the recovery process. * * @template entryPoint - The type of EntryPoint used in the smart account. * * @example * ```tsx * import { useCancelRecoveryRequest } from "@/hooks/useCancelRecoveryRequest"; * * export const CancelRecoveryButton = () => { * const { * cancelRecoveryRequest, * cancelRecoveryRequestAsync, * isLoading, * isError, * error, * isSuccess, * data * } = useCancelRecoveryRequest(); * * const handleCancel = async () => { * try { * const result = await cancelRecoveryRequestAsync({ * publicClient, * // other necessary parameters * }); * console.log('Recovery request canceled successfully:', result); * } catch (error) { * console.error('Error canceling recovery request:', error); * } * }; * * return ( * <div> * <button onClick={handleCancel} disabled={isLoading}> * Cancel Recovery Request * </button> * {isLoading && <p>Canceling recovery request...</p>} * {isError && <p>Error: {error?.message}</p>} * {isSuccess && <p>Recovery request canceled successfully. Hash: {data}</p>} * </div> * ); * }; * ``` * * @returns An object containing: * - `cancelRecoveryRequest`: A function to trigger the cancellation without waiting for the result. * - `cancelRecoveryRequestAsync`: A function to trigger the cancellation and wait for the result. * - `isLoading`: A boolean indicating if the cancellation is in progress. * - `isError`: A boolean indicating if an error occurred during cancellation. * - `error`: The error object if an error occurred, null otherwise. * - `isSuccess`: A boolean indicating if the cancellation was successful. * - `data`: The transaction hash (Hex) returned after successful cancellation. */ declare function useCancelRecoveryRequest(): UseCancelRecoveryRequestReturn; declare const useSwitchChain: () => { switchChain: (params: { chainId: number; }) => Promise<void>; switchChainAsync: (params: { chainId: number; }) => Promise<void>; isPending: boolean; error: Error | null; }; /** * Type for the getTransactionCost function. * This function doesn't return a promise, suitable for fire-and-forget usage. */ type UseGetTransactionCostMutate = (variables: EstimateUserOperationGasParameters) => void; /** * Type for the getTransactionCostAsync function. * This function returns a promise that resolves to the transaction cost in wei. */ type UseGetTransactionCostMutateAsync = (variables: EstimateUserOperationGasParameters) => Promise<{ totalGasCost: bigint; }>; type UseGetTransactionCostReturn = { data?: bigint; error: unknown; isPending: boolean; isSuccess: boolean; isError: boolean; getTransactionCost: UseGetTransactionCostMutate; getTransactionCostAsync: UseGetTransactionCostMutateAsync; }; /** * A custom hook for getting transaction costs. * * This hook provides functionality to get gas costs for transactions using the smart account client. * It can handle both single transactions and batched transactions. * * @param mutationProps Optional mutation properties from @tanstack/react-query * * @example * ```tsx * import { useGetTransactionCost } from "@/hooks/useGetTransactionCost"; * import { parseEther, type Address } from "viem"; * * export const TransactionCost = () => { * const { getTransactionCost, getTransactionCostAsync, isPending, isError, error, isSuccess, data } = useGetTransactionCost(); * * const handleGetCost = async () => { * try { * // Example of getting cost for a single transaction * const singleTxCost = await getTransactionCostAsync({ * transactions: { * to: "0x..." as Address, * value: parseEther("0.1"), * data: "0x", * } * }); * console.log("Transaction cost:", singleTxCost.totalGasCost); * * // Example of getting cost for multiple transactions * const batchTxCost = await getTransactionCostAsync({ * transactions: [ * { * to: "0x..." as Address, * value: parseEther("0.1"), * data: "0x", * }, * { * to: "0x..." as Address, * value: parseEther("0.2"), * data: "0x", * } * ] * }); * console.log("Batch transaction cost:", batchTxCost.totalGasCost); * } catch (error) { * console.error("Error getting transaction cost:", error); * } * }; * * return ( * <div> * <button onClick={handleGetCost} disabled={isPending}> * Get Transaction Cost * </button> * {isError && <p>Error: {(error as Error).message}</p>} * {isSuccess && <p>Transaction cost: {data?.toString()} wei</p>} * </div> * ); * }; * ``` * * @returns An object containing: * - `data`: The total transaction cost in wei (as bigint) * - `error`: Any error that occurred during cost calculation * - `isPending`: Whether the calculation is in progress * - `isSuccess`: Whether the calculation was successful * - `isError`: Whether an error occurred * - `getTransactionCost`: A function to trigger cost calculation without waiting for the result * - `getTransactionCostAsync`: A function to trigger cost calculation and wait for the result */ declare const useGetTransactionCost: (mutationProps?: MutationOptionsWithoutMutationFn) => UseGetTransactionCostReturn; /** * Type for the estimateGas function. * This function doesn't return a promise, suitable for fire-and-forget usage. */ type EstimateGasMutate = (variables: EstimateUserOperationGasParameters) => void; /** * Type for the estimateGasAsync function. * This function returns a promise that resolves to the detailed gas estimation. */ type EstimateGasMutateAsync = (variables: EstimateUserOperationGasParameters) => Promise<EstimateUserOperationGasReturnType>; type UseEstimateGasReturn = { data?: EstimateUserOperationGasReturnType; error: unknown; isPending: boolean; isSuccess: boolean; isError: boolean; estimateGas: EstimateGasMutate; estimateGasAsync: EstimateGasMutateAsync; }; /** * A custom hook for estimating detailed gas parameters for transactions. * * This hook provides functionality to estimate various gas parameters for transactions * using the smart account client. It can handle both single transactions and batched transactions. * * @param mutationProps Optional mutation properties from @tanstack/react-query * * @example * ```tsx * import { useEstimateGas } from "@/hooks/useEstimateGas"; * import { parseEther, type Address } from "viem"; * * export const GasEstimator = () => { * const { estimateGas, estimateGasAsync, isPending, isError, error, isSuccess, data } = useEstimateGas(); * * const handleEstimateGas = async () => { * try { * // Example of estimating gas for a single transaction * const singleTxEstimate = await estimateGasAsync({ * transactions: { * to: "0x..." as Address, * value: parseEther("0.1"), * data: "0x", * } * }); * console.log("Gas limits:", { * callGas: singleTxEstimate.callGasLimit.toString(), * verificationGas: singleTxEstimate.verificationGasLimit.toString(), * preVerificationGas: singleTxEstimate.preVerificationGas.toString(), * }); * * // Example of estimating gas for multiple transactions * const batchTxEstimate = await estimateGasAsync({ * transactions: [ * { * to: "0x..." as Address, * value: parseEther("0.1"), * data: "0x", * }, * { * to: "0x..." as Address, * value: parseEther("0.2"), * data: "0x", * } * ] * }); * console.log("Batch transaction gas parameters:", batchTxEstimate); * } catch (error) { * console.error("Error estimating gas:", error); * } * }; * * return ( * <div> * <button onClick={handleEstimateGas} disabled={isPending}> * Estimate Gas Parameters * </button> * {isError && <p>Error: {(error as Error).message}</p>} * {isSuccess && data && ( * <div> * <p>Call Gas Limit: {data.callGasLimit.toString()}</p> * <p>Verification Gas Limit: {data.verificationGasLimit.toString()}</p> * <p>Pre-verification Gas: {data.preVerificationGas.toString()}</p> * <p>Max Fee Per Gas: {data.maxFeePerGas.toString()}</p> * <p>Max Priority Fee Per Gas: {data.maxPriorityFeePerGas.toString()}</p> * </div> * )} * </div> * ); * }; * ``` * * @returns An object containing: * - `data`: Detailed gas estimation parameters including various gas limits and fees * - `error`: Any error that occurred during estimation * - `isPending`: Whether the estimation is in progress * - `isSuccess`: Whether the estimation was successful * - `isError`: Whether an error occurred * - `estimateGas`: A function to trigger gas estimation without waiting for the result * - `estimateGasAsync`: A function to trigger gas estimation and wait for the result */ declare const useEstimateGas: (mutationProps?: MutationOptionsWithoutMutationFn) => UseEstimateGasReturn; type GrantPermissionMutate = (variables: GrantPermissionParameters<ComethSafeSmartAccount>) => void; type GrantPermissionMutateAsync = (variables: GrantPermissionParameters<ComethSafeSmartAccount>) => Promise<GrantPermissionMutateResponse>; type GrantPermissionMutateResponse = { txHash: Hash; createSessionsResponse: GrantPermissionResponse; }; type UseGrantPermissionReturn = QueryResultType<GrantPermissionMutateResponse> & { grantPermission: GrantPermissionMutate; grantPermissionAsync: GrantPermissionMutateAsync; }; declare function useGrantPermission(mutationProps?: MutationOptionsWithoutMutationFn): UseGrantPermissionReturn; type SendPermissionMutate = (variables: UsePermissionParameters) => void; type SendPermissionMutateAsync = (variables: UsePermissionParameters) => Promise<Hash>; type UseSendPermissionReturn = QueryResultType<Hash> & { sendPermission: SendPermissionMutate; sendPermissionAsync: SendPermissionMutateAsync; }; declare function useSendPermission({ sessionData, privateKey, mutationProps, }: { sessionData: GrantPermissionResponse; privateKey: Hex; mutationProps?: MutationOptionsWithoutMutationFn; }): UseSendPermissionReturn; type UseSessionKeySignerReturn = QueryResultType<SafeSigner<"safeSmartSessionsSigner">>; declare function useSessionKeySigner({ sessionData, privateKey, }: { sessionData: GrantPermissionResponse; privateKey: Hex; }): UseSessionKeySignerReturn; type Session = { sessionValidator: Address; sessionValidatorInitData: Hex; salt: Hex; userOpPolicies: PolicyData[]; erc7739Policies: ERC7739Data; actions: ActionData[]; permitERC4337Paymaster: boolean; chainId: bigint; }; type PolicyData = { policy: Address; initData: Hex; }; type ERC7739Data = { allowedERC7739Content: ERC7739Context[]; erc1271Policies: PolicyData[]; }; type ERC7739Context = { appDomainSeparator: Hex; contentName: string[]; }; type ActionData = { actionTargetSelector: Hex; actionTarget: Address; actionPolicies: PolicyData[]; }; type Execution = { target: Address; value: bigint; callData: Hex; }; type PreparePermissionResponse = { /** Array of permission IDs for the created sessions. */ permissionIds: Hex[]; /** The execution object for the action. */ action: Execution; /** The sessions that were created. */ sessions: Session[]; }; declare const createSessionSmartAccountClient: (apiKey: string, smartAccountClient: ContextComethSmartAccountClient, sessionKeySigner: SafeSigner<"safeSmartSessionsSigner">) => Promise<viem.Client<viem.HttpTransport, viem.Chain, _cometh_connect_sdk_4337.ComethSafeSmartAccount, viem.BundlerRpcSchema, { grantPermission: (args: _cometh_connect_sdk_4337.GrantPermissionParameters<_cometh_connect_sdk_4337.ComethSafeSmartAccount>) => Promise<_cometh_connect_sdk_4337.GrantPermissionResponse>; preparePermission: (args: { sessionRequestedInfo: _cometh_connect_sdk_4337.CreateSessionDataParams[]; maxFeePerGas?: bigint; maxPriorityFeePerGas?: bigint; nonce?: bigint; publicClient?: { account: undefined; batch?: { multicall?: boolean | viem.Prettify<viem.MulticallBatchOptions> | undefined; } | undefined; cacheTime: number; ccipRead?: false | { request?: (parameters: viem.CcipRequestParameters) => Promise<viem__types_utils_ccip.CcipRequestReturnType>; } | undefined; chain: viem.Chain | undefined; key: string; name: string; pollingInterval: number; request: viem.EIP1193RequestFn<viem.PublicRpcSchema>; transport: viem.TransportConfig<string, viem.EIP1193RequestFn> & Record<string, any>; type: string; uid: string; call: (parameters: viem.CallParameters<viem.Chain | undefined>) => Promise<viem.CallReturnType>; createAccessList: (parameters: viem_actions.CreateAccessListParameters<viem.Chain | undefined>) => Promise<{ accessList: viem.AccessList; gasUsed: bigint; }>; createBlockFilter: () => Promise<viem.CreateBlockFilterReturnType>; createContractEventFilter: <const abi extends viem.Abi | readonly unknown[], eventName extends viem.ContractEventName<abi> | undefined, args extends viem.MaybeExtractEventArgsFromAbi<abi, eventName> | undefined, strict extends boolean | undefined = undefined, fromBlock extends viem.BlockNumber | viem.BlockTag | undefined = undefined, toBlock extends viem.BlockNumber | viem.BlockTag | undefined = undefined>(args: viem.CreateContractEventFilterParameters<abi, eventName, args, strict, fromBlock, toBlock>) => Promise<viem.CreateContractEventFilterReturnType<abi, eventName, args, strict, fromBlock, toBlock>>; createEventFilter: <const abiEvent extends viem.AbiEvent | undefined = undefined, const abiEvents extends readonly viem.AbiEvent[] | readonly unknown[] | undefined = abiEvent extends viem.AbiEvent ? [abiEvent] : undefined, strict extends boolean | undefined = undefined, fromBlock extends viem.BlockNumber | viem.BlockTag | undefined = undefined, toBlock extends viem.BlockNumber | viem.BlockTag | undefined = undefined, _EventName extends string | undefined = viem.MaybeAbiEventName<abiEvent>, _Args extends viem.MaybeExtractEventArgsFromAbi<abiEvents, _EventName> | undefined = undefined>(args?: viem.CreateEventFilterParameters<abiEvent, abiEvents, strict, fromBlock, toBlock, _EventName, _Args> | undefined) => Promise<viem.Filter<"event", abiEvents, _EventName, _Args, strict, fromBlock, toBlock> extends infer T ? { [K in keyof T]: viem.Filter<"event", abiEvents, _EventName, _Args, strict, fromBlock, toBlock>[K]; } : never>; createPendingTransactionFilter: () => Promise<viem.CreatePendingTransactionFilterReturnType>; estimateContractGas: <chain extends viem.Chain | undefined, const abi extends viem.Abi | readonly unknown[], functionName extends viem.ContractFunctionName<abi, "nonpayable" | "payable">, args extends viem.ContractFunctionArgs<abi, "nonpayable" | "payable", functionName>>(args: viem.EstimateContractGasParameters<abi, functionName, args, chain>) => Promise<viem.EstimateContractGasReturnType>; estimateGas: (args: viem.EstimateGasParameters<viem.Chain | undefined>) => Promise<viem.EstimateGasReturnType>; getBalance: (args: viem.GetBalanceParameters) => Promise<viem.GetBalanceReturnType>; getBlobBaseFee: () => Promise<viem.GetBlobBaseFeeReturnType>; getBlock: <includeTransactions extends boolean = false, blockTag extends viem.BlockTag = "latest">(args?: viem.GetBlockParameters<includeTransactions, blockTag> | undefined) => Promise<{ number: blockTag extends "pending" ? null : bigint; nonce: blockTag extends "pending" ? null : `0x${string}`; hash: blockTag extends "pending" ? null : `0x${string}`; logsBloom: blockTag extends "pending" ? null : `0x${string}`; baseFeePerGas: bigint | null; blobGasUsed: bigint; difficulty: bigint; excessBlobGas: bigint; extraData: viem.Hex; gasLimit: bigint; gasUsed: bigint; miner: viem.Address; mixHash: viem.Hash; parentBeaconBlockRoot?: `0x${string}` | undefined; parentHash: viem.Hash; receiptsRoot: viem.Hex; sealFields: viem.Hex[]; sha3Uncles: viem.Hash; size: bigint; stateRoot: viem.Hash; timestamp: bigint; totalDifficulty: bigint | null; transactionsRoot: viem.Hash; uncles: viem.Hash[]; withdrawals?: viem.Withdrawal[] | undefined | undefined; withdrawalsRoot?: `0x${string}` | undefined; transactions: includeTransactions extends true ? ({ type: "legacy"; r: viem.Hex; s: viem.Hex; v: bigint; yParity?: undefined | undefined; from: viem.Address; gas: bigint; nonce: number; to: viem.Address | null; value: bigint; blobVersionedHashes?: undefined | undefined; gasPrice: bigint; maxFeePerBlobGas?: undefined | undefined; maxFeePerGas?: undefined | undefined; maxPriorityFeePerGas?: undefined | undefined; chainId?: number | undefined; accessList?: undefined | undefined; authorizationList?: undefined | undefined; hash: viem.Hash; input: viem.Hex; typeHex: viem.Hex | null; blockNumber: (blockTag extends "pending" ? true : false) extends infer T ? T extends (blockTag extends "pending" ? true : false) ? T extends true ? null : bigint : never : never; blockHash: (blockTag extends "pending" ? true : false) extends infer T_1 ? T_1 extends (blockTag extends "pending" ? true : false) ? T_1 extends true ? null : `0x${string}` : never : never; transactionIndex: (blockTag extends "pending" ? true : false) extends infer T_2 ? T_2 extends (blockTag extends "pending" ? true : false) ? T_2 extends true ? null : number : never : never; } | { type: "eip2930"; r: viem.Hex; s: viem.Hex; v: bigint; yParity: number; from: viem.Address; gas: bigint; nonce: number; to: viem.Address | null; value: bigint; blobVersionedHashes?: undefined | undefined; gasPrice: bigint; maxFeePerBlobGas?: undefined | undefined; maxFeePerGas?: undefined | undefined; maxPriorityFeePerGas?: undefined | undefined; chainId: number; accessList: viem.AccessList; authorizationList?: undefined | undefined; hash: viem.Hash; input: viem.Hex; typeHex: viem.Hex | null; blockNumber: (blockTag extends "pending" ? true : false) extends infer T_3 ? T_3 extends (blockTag extends "pending" ? true : false) ? T_3 extends true ? null : bigint : never : never; blockHash: (blockTag extends "pending" ? true : false) extends infer T_4 ? T_4 extends (blockTag extends