wagmi-extended 0.8.0 → 1.0.1

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 (31) hide show
  1. package/README.md +224 -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/{useToken.d.ts → useFetchAssetAllowanceX.d.ts} +50 -37
  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/{useFetchAssetAllowance.d.ts → useTokenX.d.ts} +62 -108
  11. package/dist/index.cjs.js +353 -141
  12. package/dist/index.cjs.js.map +1 -1
  13. package/dist/index.d.ts +8 -4
  14. package/dist/index.esm.js +341 -138
  15. package/dist/index.esm.js.map +1 -1
  16. package/dist/utils/{errorParser.d.ts → errorParserX.d.ts} +1 -1
  17. package/package.json +2 -2
  18. package/src/config/defaults.ts +60 -0
  19. package/src/fetch-functions/fetchAllowanceX.ts +22 -0
  20. package/src/{hooks/useToken.ts → fetch-functions/fetchTokenX.ts} +42 -30
  21. package/src/hooks/useContractWriteX.ts +84 -0
  22. package/src/hooks/{useERC20Approve.ts → useERC20ApproveX.ts} +42 -38
  23. package/src/hooks/useFetchAssetAllowanceX.ts +60 -0
  24. package/src/hooks/{useHandleTransactionMutation.ts → useHandleTransactionMutationX.ts} +3 -3
  25. package/src/hooks/{useSendTransactionExtended.ts → useSendTransactionX.ts} +35 -13
  26. package/src/hooks/useTokenX.ts +65 -0
  27. package/src/index.ts +27 -4
  28. package/src/utils/{errorParser.ts → errorParserX.ts} +1 -1
  29. package/dist/hooks/useERC20Approve.d.ts +0 -28
  30. package/src/hooks/useContractWriteExtended.ts +0 -44
  31. package/src/hooks/useFetchAssetAllowance.ts +0 -94
@@ -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
+ };
@@ -3,7 +3,7 @@ import { useConfig } from "wagmi";
3
3
  import { QueryKey } from "@tanstack/query-core";
4
4
  import { Address } from "viem";
5
5
  import { useState } from "react";
6
- import { getParsedError } from "../utils/errorParser.js";
6
+ import { getParsedErrorX } from "../utils/errorParserX.js";
7
7
  import { useInvalidateQueries } from "./useInvalidateQueries.js";
8
8
 
9
9
  export type WriteExtendedAsyncParams = {
@@ -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.js";
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
+ };
package/src/index.ts CHANGED
@@ -1,4 +1,27 @@
1
- export * from "./hooks/useContractWriteExtended.js";
2
- export * from "./hooks/useSendTransactionExtended.js";
3
- export * from "./hooks/useERC20Approve.js";
4
- export * from "./utils/errorParser.js";
1
+ /* ------------- */
2
+ /* Mutations */
3
+ /* ------------- */
4
+ export * from "./hooks/useContractWriteX.js";
5
+ export * from "./hooks/useSendTransactionX.js";
6
+ export * from "./hooks/useERC20ApproveX.js";
7
+
8
+ /* ------------- */
9
+ /* Queries */
10
+ /* ------------- */
11
+ export * from "./hooks/useTokenX.js";
12
+ export * from "./hooks/useFetchAssetAllowanceX.js";
13
+
14
+ /* ------------- */
15
+ /* Fetch */
16
+ /* ------------- */
17
+ export * from "./fetch-functions/fetchTokenX.js";
18
+
19
+ /* ------------- */
20
+ /* Utils */
21
+ /* ------------- */
22
+ export * from "./utils/errorParserX.js";
23
+
24
+ /* ------------- */
25
+ /* Config */
26
+ /* ------------- */
27
+ export * from "./config/defaults.js";
@@ -77,7 +77,7 @@ export const getErrorMapping = (): Record<string, string> =>
77
77
  * const message = getParsedError(someError);
78
78
  * console.log(message); // Outputs a custom error message or a default error message.
79
79
  */
80
- export const getParsedError = (error: any | BaseError): string => {
80
+ export const getParsedErrorX = (error: any | BaseError): string => {
81
81
  const defaultMessage = "An unknown error occurred. Please contact support.";
82
82
  let message = defaultMessage;
83
83
  let errorKey = "";
@@ -1,28 +0,0 @@
1
- import { Address } from "viem";
2
- /**
3
- * Helper function to determine human readable state of approve.
4
- *
5
- * @param {boolean} isApproved - Indicates if the approval is already done.
6
- * @param {boolean} justApproved - Indicates if the user has just approved.
7
- * @return {string} - The appropriate button text.
8
- */
9
- export declare function getApproveState(isApproved?: boolean, justApproved?: boolean): "Approve Confirmed" | "Approved" | "Approve";
10
- /**
11
- * Custom hook for approving ERC20 token transfers.
12
- *
13
- * This hook provides functionality for approving ERC20 token transfers, checking the current allowance, and handling the approval transaction using Wagmi.
14
- *
15
- * @param {Address} tokenAddress - The address of the ERC20 token contract.
16
- * @param {Address} spenderAddress - The address of the spender to approve the transfer to.
17
- * @param {bigint} [amount=BigInt(0)] - The amount of tokens to approve for transfer. Defaults to 0.
18
- * @returns {Object} Object containing the following properties:
19
- * - {boolean} isApproved - Indicates whether the spender is already approved to transfer the specified amount of tokens.
20
- * - {boolean} isApproving - Indicates whether an approval transaction is currently pending.
21
- * - {Function} approveAsync - Function to trigger the approval transaction.
22
- */
23
- export declare const useERC20Approve: (tokenAddress?: Address, spenderAddress?: Address, amount?: bigint) => {
24
- isApproved: boolean;
25
- isApproving: boolean;
26
- justApproved: boolean;
27
- approveAsync: () => Promise<void>;
28
- };
@@ -1,44 +0,0 @@
1
- import { useWriteContract } from "wagmi";
2
- import {
3
- WriteExtendedAsyncParams,
4
- useHandleTransactionMutation,
5
- } from "./useHandleTransactionMutation.js";
6
-
7
- /**
8
- * Custom hook for writing to a smart contract using Wagmi.
9
- *
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.
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
- export function useContractWriteExtended(settings?: WriteExtendedAsyncParams) {
26
- const { isPending, errorMessage, onMutate, onSettled } =
27
- useHandleTransactionMutation({
28
- settings,
29
- });
30
-
31
- const { writeContractAsync, ...rest } = useWriteContract({
32
- mutation: {
33
- onMutate,
34
- onSettled,
35
- },
36
- });
37
-
38
- return {
39
- ...rest,
40
- isPending,
41
- errorMessage,
42
- writeContractAsync,
43
- };
44
- }
@@ -1,94 +0,0 @@
1
- import { useQuery, useQueryClient } from "@tanstack/react-query";
2
- import { Address, erc20Abi } from "viem";
3
- import { readContract } from "viem/actions";
4
- import { useAccount, useConfig } from "wagmi";
5
- import { fetchToken } from "./useToken.js";
6
- import { queryConfig } from "../query-config/index.js";
7
-
8
- export const fetchAllowance = async (
9
- asset: Address,
10
- spender: Address,
11
- userAddress: Address,
12
- queryClient: any,
13
- config: any
14
- ) => {
15
- const [tokenData, allowance] = await Promise.all([
16
- fetchToken(asset, queryClient, config),
17
- readContract(config, {
18
- address: asset,
19
- abi: erc20Abi,
20
- functionName: "allowance",
21
- args: [userAddress, spender],
22
- }),
23
- ]);
24
-
25
- if (!tokenData || allowance == null) {
26
- throw new Error("Failed to fetch token data or allowance");
27
- }
28
-
29
- return {
30
- bigIntValue: allowance,
31
- decimals: tokenData.decimals,
32
- symbol: tokenData.symbol,
33
- };
34
- };
35
-
36
- const HookFetchAssetAllowanceQK = (
37
- asset: Address,
38
- spender: Address,
39
- userAddress: Address,
40
- config: any,
41
- queryClient: any
42
- ) =>
43
- [
44
- "hookFetchAllowance",
45
- asset,
46
- spender,
47
- userAddress,
48
- config,
49
- queryClient,
50
- ] as const;
51
-
52
- /**
53
- * Custom hook for fetching asset allowance.
54
- *
55
- * @param {Address} asset - The address of the ERC20 token contract.
56
- * @param {Address} spender - The address of the spender to check allowance for.
57
- */
58
- export const useFetchAssetAllowance = ({
59
- asset,
60
- spender,
61
- }: {
62
- asset?: Address;
63
- spender?: Address;
64
- }) => {
65
- const config = useConfig();
66
- const queryClient = useQueryClient();
67
- const { address: userAddress } = useAccount();
68
-
69
- const { data, ...rest } = useQuery({
70
- queryKey: HookFetchAssetAllowanceQK(
71
- asset!,
72
- spender!,
73
- userAddress!,
74
- config,
75
- queryClient
76
- ),
77
- queryFn: () =>
78
- fetchAllowance(asset!, spender!, userAddress!, queryClient, config),
79
- enabled: !!asset && !!spender && !!userAddress,
80
- ...queryConfig.sensitiveDataQueryConfig,
81
- });
82
-
83
- return {
84
- ...rest,
85
- data,
86
- queryKey: HookFetchAssetAllowanceQK(
87
- asset!,
88
- spender!,
89
- userAddress!,
90
- config,
91
- queryClient
92
- ),
93
- };
94
- };