wagmi-extended 0.5.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +220 -1
  2. package/dist/config/defaults.d.ts +40 -0
  3. package/dist/fetch-functions/fetchAllowanceX.d.ts +2 -0
  4. package/dist/fetch-functions/fetchTokenX.d.ts +24 -0
  5. package/dist/hooks/{useContractWriteExtended.d.ts → useContractWriteX.d.ts} +43 -3
  6. package/dist/hooks/useERC20ApproveX.d.ts +40 -0
  7. package/dist/hooks/useFetchAssetAllowanceX.d.ts +192 -0
  8. package/dist/hooks/{useHandleTransactionMutation.d.ts → useHandleTransactionMutationX.d.ts} +1 -1
  9. package/dist/hooks/{useSendTransactionExtended.d.ts → useSendTransactionX.d.ts} +31 -10
  10. package/dist/hooks/useTokenX.d.ts +204 -0
  11. package/dist/index.cjs.js +456 -27
  12. package/dist/index.cjs.js.map +1 -1
  13. package/dist/index.d.ts +8 -3
  14. package/dist/index.esm.js +446 -28
  15. package/dist/index.esm.js.map +1 -1
  16. package/dist/query-config/index.d.ts +8 -0
  17. package/dist/utils/{errorParser.d.ts → errorParserX.d.ts} +1 -1
  18. package/package.json +2 -2
  19. package/src/config/defaults.ts +60 -0
  20. package/src/fetch-functions/fetchAllowanceX.ts +22 -0
  21. package/src/fetch-functions/fetchTokenX.ts +134 -0
  22. package/src/hooks/useContractWriteX.ts +84 -0
  23. package/src/hooks/useERC20ApproveX.ts +108 -0
  24. package/src/hooks/useFetchAssetAllowanceX.ts +60 -0
  25. package/src/hooks/{useHandleTransactionMutation.ts → useHandleTransactionMutationX.ts} +4 -4
  26. package/src/hooks/{useSendTransactionExtended.ts → useSendTransactionX.ts} +35 -13
  27. package/src/hooks/useTokenX.ts +65 -0
  28. package/src/index.ts +27 -3
  29. package/src/query-config/index.ts +8 -0
  30. package/src/utils/{errorParser.ts → errorParserX.ts} +1 -1
  31. package/tsconfig.json +9 -1
  32. package/src/hooks/useContractWriteExtended.ts +0 -44
@@ -0,0 +1,8 @@
1
+ export declare const queryConfig: {
2
+ metadataQueryConfig: {
3
+ staleTime: number;
4
+ };
5
+ sensitiveDataQueryConfig: {
6
+ staleTime: number;
7
+ };
8
+ };
@@ -44,4 +44,4 @@ export declare const getErrorMapping: () => Record<string, string>;
44
44
  * const message = getParsedError(someError);
45
45
  * console.log(message); // Outputs a custom error message or a default error message.
46
46
  */
47
- export declare const getParsedError: (error: any | BaseError) => string;
47
+ export declare const getParsedErrorX: (error: any | BaseError) => string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wagmi-extended",
3
- "version": "0.5.0",
3
+ "version": "1.0.0",
4
4
  "type": "module",
5
5
  "description": "A library providing extended hooks on top of Wagmi with additional features.",
6
6
  "main": "dist/index.cjs.js",
@@ -30,7 +30,7 @@
30
30
  "license": "MIT",
31
31
  "scripts": {
32
32
  "clean": "rimraf dist",
33
- "build": "npm run clean && npm version minor && rollup -c --bundleConfigAsCjs",
33
+ "build": "npm run clean && rollup -c --bundleConfigAsCjs",
34
34
  "prepublishOnly": "npm run build"
35
35
  },
36
36
  "peerDependencies": {
@@ -0,0 +1,60 @@
1
+ // src/config/defaults.ts
2
+ import { QueryClient } from "@tanstack/react-query";
3
+ import { Config } from "wagmi";
4
+
5
+ // You can adjust the type for wagmiConfig to match your needs.
6
+ let defaultQueryClient: QueryClient | null = null;
7
+ let defaultWagmiConfig: any = null;
8
+
9
+ /**
10
+ * Sets the default configuration values.
11
+ *
12
+ * @param queryClient - The default QueryClient instance.
13
+ * @param wagmiConfig - The default Wagmi configuration.
14
+ * @example
15
+ * //In your application initialization (e.g., index.tsx or App.tsx):
16
+ * import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
17
+ * import { wagmiConfig } from "/path/to/wagmi-config";
18
+ * import { setDefaults } from "wagmi-extended";
19
+ *
20
+ * const queryClient = new QueryClient();
21
+ *
22
+ * //Set defaults for the extended library functions.
23
+ * setDefaults(queryClient, wagmiConfig);
24
+ *
25
+ * //Now helper functions like fetchTokenX can use these defaults if no explicit parameters are provided.
26
+ */
27
+ export function setDefaults(
28
+ queryClient: QueryClient,
29
+ wagmiConfig: Config
30
+ ): void {
31
+ defaultQueryClient = queryClient;
32
+ defaultWagmiConfig = wagmiConfig;
33
+ }
34
+
35
+ /**
36
+ * Retrieves the currently set default configurations.
37
+ *
38
+ * @throws Will throw an error if defaults are not initialized.
39
+ * @returns An object containing the default queryClient and wagmiConfig.
40
+ *
41
+ * @example
42
+ * // Usage in a helper function:
43
+ * import { getDefaults } from "wagmi-extended";
44
+ *
45
+ * function exampleFunction() {
46
+ * const { queryClient, wagmiConfig } = getDefaults();
47
+ * // Use queryClient and wagmiConfig as needed...
48
+ * }
49
+ */
50
+ export function getDefaults(): {
51
+ queryClient: QueryClient;
52
+ wagmiConfig: Config;
53
+ } {
54
+ if (!defaultQueryClient || !defaultWagmiConfig) {
55
+ throw new Error(
56
+ "Default configuration not set. Please call setDefaults() first."
57
+ );
58
+ }
59
+ return { queryClient: defaultQueryClient, wagmiConfig: defaultWagmiConfig };
60
+ }
@@ -0,0 +1,22 @@
1
+ import { Address, erc20Abi } from "viem";
2
+ import { readContract } from "viem/actions";
3
+
4
+ export const fetchAllowance = async (
5
+ asset: Address,
6
+ spender: Address,
7
+ userAddress: Address,
8
+ config: any
9
+ ) => {
10
+ const allowance = await readContract(config, {
11
+ address: asset,
12
+ abi: erc20Abi,
13
+ functionName: "allowance",
14
+ args: [userAddress, spender],
15
+ });
16
+
17
+ if (allowance == null) {
18
+ throw new Error("Failed to fetch token data or allowance");
19
+ }
20
+
21
+ return allowance;
22
+ };
@@ -0,0 +1,134 @@
1
+ import { QueryClient } from "@tanstack/react-query";
2
+ import { readContractQueryOptions } from "wagmi/query";
3
+ import { Address, zeroAddress, erc20Abi } from "viem";
4
+ import { Config } from "wagmi";
5
+ import { getDefaults } from "../config/defaults.js";
6
+ import { queryConfig } from "../query-config/index.js";
7
+
8
+ export interface Token {
9
+ symbol: string;
10
+ decimals: number;
11
+ name: string;
12
+ }
13
+
14
+ export const EthTokenData: Token = {
15
+ symbol: "ETH",
16
+ decimals: 18,
17
+ name: "Ethereum",
18
+ };
19
+
20
+ export async function fetchDecimalsX(
21
+ token: Address,
22
+ queryClient?: QueryClient,
23
+ wagmiConfig?: Config
24
+ ): Promise<number | undefined> {
25
+ if (!queryClient || !wagmiConfig) {
26
+ ({ queryClient, wagmiConfig } = getDefaults());
27
+ }
28
+ if (!queryClient || !wagmiConfig) {
29
+ throw new Error(
30
+ "Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()"
31
+ );
32
+ }
33
+
34
+ if (token === zeroAddress) return EthTokenData.decimals;
35
+
36
+ const decimals = await queryClient.fetchQuery({
37
+ ...readContractQueryOptions(wagmiConfig, {
38
+ address: token,
39
+ abi: erc20Abi,
40
+ functionName: "decimals",
41
+ }),
42
+ ...queryConfig.metadataQueryConfig,
43
+ });
44
+
45
+ return decimals;
46
+ }
47
+
48
+ export async function fetchSymbolX(
49
+ token: Address,
50
+ queryClient?: QueryClient,
51
+ wagmiConfig?: Config
52
+ ): Promise<string> {
53
+ if (!queryClient || !wagmiConfig) {
54
+ ({ queryClient, wagmiConfig } = getDefaults());
55
+ }
56
+ if (!queryClient || !wagmiConfig) {
57
+ throw new Error(
58
+ "Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()"
59
+ );
60
+ }
61
+
62
+ if (token === zeroAddress) return EthTokenData.symbol;
63
+
64
+ const symbol = await queryClient.fetchQuery({
65
+ ...readContractQueryOptions(wagmiConfig, {
66
+ address: token,
67
+ abi: erc20Abi,
68
+ functionName: "symbol",
69
+ }),
70
+ ...queryConfig.metadataQueryConfig,
71
+ });
72
+
73
+ return symbol;
74
+ }
75
+
76
+ export async function fetchNameX(
77
+ token: Address,
78
+ queryClient: any,
79
+ wagmiConfig: any
80
+ ): Promise<string> {
81
+ if (token === zeroAddress) return EthTokenData.name;
82
+
83
+ if (!queryClient || !wagmiConfig) {
84
+ ({ queryClient, wagmiConfig } = getDefaults());
85
+ }
86
+ if (!queryClient || !wagmiConfig) {
87
+ throw new Error(
88
+ "Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()"
89
+ );
90
+ }
91
+
92
+ const name = await queryClient.fetchQuery({
93
+ ...readContractQueryOptions(wagmiConfig, {
94
+ address: token,
95
+ abi: erc20Abi,
96
+ functionName: "name",
97
+ }),
98
+ ...queryConfig.metadataQueryConfig,
99
+ });
100
+
101
+ return name;
102
+ }
103
+
104
+ /**
105
+ * Fetches the token metadata (symbol, decimals) for the given token address.
106
+ * Internally calls:
107
+ * - `fetchSymbol(token)` to retrieve the token symbol,
108
+ * - `fetchDecimals(token)` to retrieve the token decimals
109
+ * - `fetchName(token)` to retrieve the token name
110
+ *
111
+ * @param token - The address of the token.
112
+ * @returns A `Token` object containing the symbol, decimals.
113
+ * @throws Will throw an error if symbol or decimals cannot be fetched.
114
+ */
115
+ export async function fetchTokenX(
116
+ token: Address,
117
+ queryClient: any,
118
+ wagmiConfig: any
119
+ ): Promise<Token> {
120
+ const [symbol, decimals, name] = await Promise.all([
121
+ fetchSymbolX(token, queryClient, wagmiConfig),
122
+ fetchDecimalsX(token, queryClient, wagmiConfig),
123
+ fetchNameX(token, queryClient, wagmiConfig),
124
+ ]);
125
+ if (!symbol || !decimals || !name) {
126
+ throw new Error("Failed to fetch token data");
127
+ }
128
+
129
+ return {
130
+ symbol,
131
+ decimals,
132
+ name,
133
+ };
134
+ }
@@ -0,0 +1,84 @@
1
+ import { useWriteContract } from "wagmi";
2
+ import {
3
+ WriteExtendedAsyncParams,
4
+ useHandleTransactionMutationX,
5
+ } from "./useHandleTransactionMutationX.js";
6
+
7
+ /**
8
+ * Custom hook for writing to a smart contract using Wagmi.
9
+ *
10
+ * This hook provides functionality for writing a contract using Wagmi, handling the asynchronous nature of the operation, waiting for the transaction receipt, and error handling.
11
+ *
12
+ * @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.
13
+ * @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.
14
+ * @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.
15
+ * @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.
16
+ * @param {Function} [settings.onError] - Callback function to be called on transaction error.
17
+ * @param {Function} [settings.onSettled] - Callback function to be called after the transaction settles (whether success or failure).
18
+ * @param {QueryKey[]} [settings.queriesToInvalidate] - Array of query keys to invalidate after the transaction receives a receipt.
19
+ * @returns {Object} Object containing the following properties:
20
+ * - {boolean} isPending - Indicates whether the transaction is pending.
21
+ * - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.
22
+ * - {Function} writeContractAsync - Function to trigger the write operation.
23
+ *
24
+ /**
25
+ * Custom hook for writing a contract using Wagmi with extended functionality.
26
+ *
27
+ * This hook wraps Wagmi’s `useContractWriteX` with additional handling for
28
+ * waiting for a transaction receipt, logging control, and invalidation of specified queries.
29
+ *
30
+ * @param {WriteExtendedAsyncParams} [settings] - Optional settings for handling the transaction.
31
+ * @returns {Object} An object containing:
32
+ * - `isPending`: {boolean} indicating if the transaction is in progress.
33
+ * - `errorMessage`: {string|undefined} a potential error message.
34
+ * - `writeContractAsync`: {Function} a function to trigger the transaction.
35
+ *
36
+ * @example
37
+ * // In your component:
38
+ * function MyTransactionComponent() {
39
+ * const { writeContractAsync, isPending, errorMessage } = useContractWriteX({
40
+ * onSuccess: (txHash) => console.log("Transaction successful:", txHash),
41
+ * onError: (error) => console.error("Transaction error:", error),
42
+ * queriesToInvalidate: [["userBalance"], ["userActivity"]],
43
+ * });
44
+ *
45
+ * const handleWrite = async () => {
46
+ * try {
47
+ * const txHash = await writeContractAsync({ transaction params here.. });
48
+ * console.log("Received txHash:", txHash);
49
+ * } catch (err) {
50
+ * console.error("Failed writing transaction:", err);`
51
+ * }
52
+ * };
53
+ *
54
+ * return (
55
+ * <div>
56
+ * <button onClick={handleWrite} disabled={isPending}>
57
+ * {isPending ? "Processing..." : "Write Transaction"}
58
+ * </button>
59
+ * {errorMessage && <p>Error: {errorMessage}</p>}
60
+ * </div>
61
+ * );
62
+ * }
63
+ */
64
+
65
+ export function useContractWriteX(settings?: WriteExtendedAsyncParams) {
66
+ const { isPending, errorMessage, onMutate, onSettled } =
67
+ useHandleTransactionMutationX({
68
+ settings,
69
+ });
70
+
71
+ const { writeContractAsync, ...rest } = useWriteContract({
72
+ mutation: {
73
+ onMutate,
74
+ onSettled,
75
+ },
76
+ });
77
+
78
+ return {
79
+ ...rest,
80
+ isPending,
81
+ errorMessage,
82
+ writeContractAsync,
83
+ };
84
+ }
@@ -0,0 +1,108 @@
1
+ import { useState, useEffect } from "react";
2
+ import { Address, maxUint256, erc20Abi } from "viem";
3
+ import { useFetchAssetAllowanceX } from "./useFetchAssetAllowanceX.js";
4
+ import { useContractWriteX } from "./useContractWriteX.js";
5
+
6
+ /**
7
+ * Custom hook for approving ERC20 token transfers.
8
+ *
9
+ * This hook provides functionality for approving ERC20 token transfers, checking the current allowance, and handling the approval transaction using Wagmi.
10
+ *
11
+ * @param {Address} tokenAddress - The address of the ERC20 token contract (the transfer from).
12
+ * @param {Address} spenderAddress - The address of the spender to approve the transfer to.
13
+ * @param {bigint} [amount=BigInt(0)] - The amount to approve for transfer. Defaults to undefined.
14
+ * @param {boolean} [approveMax=false] - Indicates whether to approve the maximum amount or a specific amount.
15
+ * @returns {Object} Object containing the following properties:
16
+ * - {boolean} isApproved - Indicates whether the spender is already approved to transfer the specified amount of tokens.
17
+ * - {boolean} isApproving - Indicates whether an approval transaction is currently pending.
18
+ * - {Function} approveAsync - Function to trigger the approval transaction.
19
+ *
20
+ * @example
21
+ * // In your component:
22
+ * function ApproveTokenButton(amountToApprove) {
23
+ * const tokenAddress = "0xTokenAddressExample";
24
+ * const spenderAddress = "0xSpenderAddressExample";
25
+ *
26
+ * const { isApproved, isApproving, justApproved, approveAsync } = useERC20ApproveX(
27
+ * tokenAddress,
28
+ * spenderAddress,
29
+ * parseUnits(amountToApprove.toString(), 18),
30
+ * );
31
+ *
32
+ * return (
33
+ * <button onClick={approveAsync} disabled={isApproving || isApproved}>
34
+ * {isApproving ? "Approving..." : isApproved ? "Approved" : "Approve Token"}
35
+ * </button>
36
+ * );
37
+ * }
38
+ */
39
+
40
+ export const useERC20ApproveX = (
41
+ tokenAddress?: Address,
42
+ spenderAddress?: Address,
43
+ amount?: bigint,
44
+ approveMax?: boolean
45
+ ) => {
46
+ const [isApproved, setIsApproved] = useState(false);
47
+ const [justApproved, setJustApproved] = useState(false);
48
+
49
+ const { data: allowance, queryKey: allowanceKQ } = useFetchAssetAllowanceX({
50
+ asset: tokenAddress,
51
+ spender: spenderAddress,
52
+ });
53
+
54
+ const { writeContractAsync: approveTokenAsync, isPending } =
55
+ useContractWriteX({
56
+ queriesToInvalidate: [allowanceKQ],
57
+ });
58
+
59
+ useEffect(() => {
60
+ if (amount == null) {
61
+ setIsApproved(false);
62
+ } else if (allowance && allowance >= amount) {
63
+ setIsApproved(true);
64
+ } else {
65
+ setIsApproved(false);
66
+ }
67
+ }, [allowance, amount]);
68
+
69
+ const approveAsync = async () => {
70
+ const amountToApprove = approveMax ? maxUint256 : amount;
71
+
72
+ try {
73
+ if (!spenderAddress) {
74
+ throw new Error("spenderAddress is undefined!");
75
+ }
76
+ if (!tokenAddress) {
77
+ throw new Error("tokenAddress is undefined!");
78
+ }
79
+ if (amountToApprove == null) {
80
+ throw new Error("amountToApprove is undefined!");
81
+ }
82
+
83
+ await approveTokenAsync(
84
+ {
85
+ address: tokenAddress,
86
+ abi: erc20Abi,
87
+ functionName: "approve",
88
+ args: [spenderAddress, amountToApprove],
89
+ },
90
+ {
91
+ onSuccess: () => {
92
+ setJustApproved(true);
93
+ },
94
+ }
95
+ );
96
+ } catch (e: any) {
97
+ console.error("Error approving token:", e);
98
+ throw e;
99
+ }
100
+ };
101
+
102
+ return {
103
+ isApproved,
104
+ isApproving: isPending,
105
+ justApproved,
106
+ approveAsync,
107
+ };
108
+ };
@@ -0,0 +1,60 @@
1
+ import { useQuery, useQueryClient } from "@tanstack/react-query";
2
+ import { Address, erc20Abi } from "viem";
3
+ import { useAccount, useConfig } from "wagmi";
4
+ import { queryConfig } from "../query-config/index.js";
5
+ import { fetchAllowance } from "../fetch-functions/fetchAllowanceX.js";
6
+
7
+ const HookFetchAssetAllowanceQK = (
8
+ asset?: Address,
9
+ spender?: Address,
10
+ userAddress?: Address
11
+ ) => ["HookFetchAllowance", asset, spender, userAddress] as const;
12
+
13
+ /**
14
+ * Custom hook for fetching asset allowance.
15
+ *
16
+ * @param {Address} asset - The address of the ERC20 token contract.
17
+ * @param {Address} spender - The address of the spender to check allowance for.
18
+ *
19
+ *
20
+ * @example
21
+ * // In your component:
22
+ * function AllowanceDisplay() {
23
+ * const { data: allowance, isLoading, error } = useFetchAssetAllowanceX({
24
+ * asset: "0xTokenAddressExample",
25
+ * spender: "0xSpenderAddressExample",
26
+ * });
27
+ *
28
+ * if (isLoading) return <div>Loading allowance...</div>;
29
+ * if (error) return <div>Error loading allowance</div>;
30
+ *
31
+ * return (
32
+ * <div>
33
+ * Current Allowance: {allowance}
34
+ * </div>
35
+ * );
36
+ * }
37
+ */
38
+ export const useFetchAssetAllowanceX = ({
39
+ asset,
40
+ spender,
41
+ }: {
42
+ asset?: Address;
43
+ spender?: Address;
44
+ }) => {
45
+ const config = useConfig();
46
+ const { address: userAddress } = useAccount();
47
+
48
+ const { data, ...rest } = useQuery({
49
+ queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),
50
+ queryFn: () => fetchAllowance(asset!, spender!, userAddress!, config),
51
+ enabled: Boolean(asset) && Boolean(spender) && Boolean(userAddress),
52
+ ...queryConfig.sensitiveDataQueryConfig,
53
+ });
54
+
55
+ return {
56
+ ...rest,
57
+ data,
58
+ queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),
59
+ };
60
+ };
@@ -1,10 +1,10 @@
1
1
  import { waitForTransactionReceipt } from "wagmi/actions";
2
- import { useInvalidateQueries } from "./useInvalidateQueries";
3
2
  import { useConfig } from "wagmi";
4
3
  import { QueryKey } from "@tanstack/query-core";
5
4
  import { Address } from "viem";
6
5
  import { useState } from "react";
7
- import { getParsedError } from "../utils/errorParser";
6
+ import { getParsedErrorX } from "../utils/errorParserX.js";
7
+ import { useInvalidateQueries } from "./useInvalidateQueries.js";
8
8
 
9
9
  export type WriteExtendedAsyncParams = {
10
10
  onSuccess?: (txHash: Address) => void;
@@ -20,7 +20,7 @@ export type WriteExtendedAsyncParams = {
20
20
  *
21
21
  * @returns {Function} A shared `onSettled` callback for transaction mutations.
22
22
  */
23
- export function useHandleTransactionMutation({
23
+ export function useHandleTransactionMutationX({
24
24
  settings,
25
25
  }: {
26
26
  settings?: WriteExtendedAsyncParams;
@@ -74,7 +74,7 @@ export function useHandleTransactionMutation({
74
74
  // 6. return result
75
75
  return txHash;
76
76
  } catch (error) {
77
- const parsedError = getParsedError(error);
77
+ const parsedError = getParsedErrorX(error);
78
78
 
79
79
  if (!settings?.disableLogging) {
80
80
  // 1. log error
@@ -1,21 +1,15 @@
1
- import { Hash } from "viem";
2
1
  import { useSendTransaction } from "wagmi";
3
- import { QueryKey } from "@tanstack/query-core";
4
- import { useHandleTransactionMutation } from "./useHandleTransactionMutation";
5
-
6
- export type SeamlessSendAsyncParams = {
7
- onSuccess?: (txHash: Hash) => void;
8
- onError?: (e: any) => void;
9
- onSettled?: () => void;
10
- queriesToInvalidate?: (QueryKey | undefined)[];
11
- };
2
+ import {
3
+ useHandleTransactionMutationX,
4
+ WriteExtendedAsyncParams,
5
+ } from "./useHandleTransactionMutationX.js";
12
6
 
13
7
  /**
14
8
  * Custom hook for sending a transaction using Wagmi.
15
9
  *
16
10
  * This hook provides functionality for sending a transaction using Wagmi, handling the asynchronous nature of the operation, waiting for the transaction receipt, and error handling.
17
11
  *
18
- * @param {SeamlessWriteAsyncParams} [settings] - Optional settings for the write operation.
12
+ * @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.
19
13
  * @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.
20
14
  * @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.
21
15
  * @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.
@@ -26,11 +20,39 @@ export type SeamlessSendAsyncParams = {
26
20
  * - {boolean} isPending - Indicates whether the transaction is pending.
27
21
  * - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.
28
22
  * - {Function} sendTransactionAsync - Function to trigger the send transaction mutation.
23
+
24
+ * @example
25
+ * // In your component:
26
+ * function MyTransactionComponent() {
27
+ * const { sendTransactionAsync, isPending, errorMessage } = useSendTransactionX({
28
+ * onSuccess: (txHash) => console.log("Transaction successful:", txHash),
29
+ * onError: (error) => console.error("Transaction error:", error),
30
+ * queriesToInvalidate: [["userBalance"], ["userActivity"]],
31
+ * });
32
+ *
33
+ * const handleSend = async () => {
34
+ * try {
35
+ * const txHash = await sendTransactionAsync({ transaction params here.. });
36
+ * console.log("Received txHash:", txHash);
37
+ * } catch (err) {
38
+ * console.error("Failed sending transaction:", err);`
39
+ * }
40
+ * };
41
+ *
42
+ * return (
43
+ * <div>
44
+ * <button onClick={handleSend} disabled={isPending}>
45
+ * {isPending ? "Processing..." : "Send Transaction"}
46
+ * </button>
47
+ * {errorMessage && <p>Error: {errorMessage}</p>}
48
+ * </div>
49
+ * );
50
+ * }
29
51
  */
30
52
 
31
- export function useSendTransactionExtended(settings?: SeamlessSendAsyncParams) {
53
+ export function useSendTransactionX(settings?: WriteExtendedAsyncParams) {
32
54
  const { isPending, errorMessage, onMutate, onSettled } =
33
- useHandleTransactionMutation({
55
+ useHandleTransactionMutationX({
34
56
  settings,
35
57
  });
36
58
 
@@ -0,0 +1,65 @@
1
+ import { useQueryClient, useQuery } from "@tanstack/react-query";
2
+ import { Address } from "viem";
3
+ import { useConfig } from "wagmi";
4
+ import { fetchTokenX } from "../fetch-functions/fetchTokenX.js";
5
+
6
+ /**
7
+ * Returns a query key for fetching token data.
8
+ *
9
+ * @param {Address | undefined} asset - The token address.
10
+ * @returns {Array} A unique query key for the token fetch.
11
+ *
12
+ * @example
13
+ * const queryKey = HookFetchTokenQK("0x123...");
14
+ */
15
+ export const HookFetchTokenQK = (asset?: Address): any[] => [
16
+ "HookTokenWagmiExtended",
17
+ asset,
18
+ ];
19
+
20
+ /**
21
+ * Custom hook for fetching token metadata using extended Wagmi functionality.
22
+ *
23
+ * This hook leverages React Query for data fetching and caching.
24
+ * It retrieves token metadata (such as symbol, decimals, name, etc.) for a given token address.
25
+ *
26
+ * @param {Address} [asset] - The token address.
27
+ * @returns {Object} An object with the following properties:
28
+ * - `data`: The token data (or undefined if not loaded).
29
+ * - `isLoading`: Boolean indicating if the data is loading.
30
+ * - `error`: Any error encountered during the fetch.
31
+ * - `queryKey`: The unique key used for the query.
32
+ *
33
+ * @example
34
+ * // In your component:
35
+ * function MyTokenComponent() {
36
+ * const { data, isLoading, error, queryKey } = useTokenX("0x123456...");
37
+ *
38
+ * if (isLoading) return <div>Loading token data...</div>;
39
+ * if (error) return <div>Error: {error.message}</div>;
40
+ *
41
+ * return (
42
+ * <div>
43
+ * <p>Token Symbol: {data.symbol}</p>
44
+ * <p>Decimals: {data.decimals}</p>
45
+ * <p>Name: {data.name}</p>
46
+ * </div>
47
+ * );
48
+ * }
49
+ */
50
+ export const useTokenX = (asset?: Address) => {
51
+ const queryClient = useQueryClient();
52
+ const config = useConfig();
53
+
54
+ const { data, ...rest } = useQuery({
55
+ queryKey: HookFetchTokenQK(asset),
56
+ queryFn: () => fetchTokenX(asset!, queryClient, config),
57
+ enabled: Boolean(asset),
58
+ });
59
+
60
+ return {
61
+ ...rest,
62
+ data,
63
+ queryKey: HookFetchTokenQK(asset),
64
+ };
65
+ };