wagmi-extended 1.1.6 → 1.1.8
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.
- package/README.md +27 -4
- package/dist/index.cjs.js +3 -4
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +3 -4
- package/dist/index.esm.js.map +1 -1
- package/package.json +1 -1
- package/src/hooks/useERC20ApproveX.ts +9 -13
package/README.md
CHANGED
|
@@ -111,6 +111,11 @@ Example:
|
|
|
111
111
|
function MyTransactionComponent() {
|
|
112
112
|
const { writeContractAsync, isPending, errorMessage } = useContractWriteX({
|
|
113
113
|
queriesToInvalidate: [["userBalance"], ["userActivity"]],
|
|
114
|
+
{
|
|
115
|
+
// use calbacks here in writeContractAsync or in useContractWriteX
|
|
116
|
+
onSuccess: (txHash) => console.log("Transaction successful:", txHash),
|
|
117
|
+
onError: (error) => console.error("Transaction error:", error),
|
|
118
|
+
}
|
|
114
119
|
});
|
|
115
120
|
|
|
116
121
|
const handleWrite = async () => {
|
|
@@ -120,10 +125,6 @@ const handleWrite = async () => {
|
|
|
120
125
|
abi: [], // Provide your contract ABI
|
|
121
126
|
functionName: "executeFunction",
|
|
122
127
|
args: [/* function arguments */],
|
|
123
|
-
}, {
|
|
124
|
-
// use calbacks here in writeContractAsync or in useContractWriteX
|
|
125
|
-
onSuccess: (txHash) => console.log("Transaction successful:", txHash),
|
|
126
|
-
onError: (error) => console.error("Transaction error:", error),
|
|
127
128
|
});
|
|
128
129
|
console.log("Received txHash:", txHash);
|
|
129
130
|
} catch (err) {
|
|
@@ -142,6 +143,28 @@ return (
|
|
|
142
143
|
}
|
|
143
144
|
```
|
|
144
145
|
|
|
146
|
+
**Important:** To ensure transaction receipts are awaited correctly, **all settings and callbacks must be passed inside the hook itself**, not inside `mutate` or `mutateAsync` calls.
|
|
147
|
+
|
|
148
|
+
Example of correct usage:
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
const { writeContractAsync } = useContractWriteX({
|
|
152
|
+
queriesToInvalidate: [["userBalance"]],
|
|
153
|
+
onSuccess: (txHash) => console.log("Tx success:", txHash),
|
|
154
|
+
onError: (err) => console.error("Tx error:", err),
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
**Avoid passing callbacks like this:**
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
await writeContractAsync(config, {
|
|
162
|
+
onSuccess: () => {}, // ❌ This will NOT guarantee receipt handling!
|
|
163
|
+
});
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
This design ensures that `wagmi-extended` can properly track and wait for the transaction receipt, giving your app reliable post-transaction state.
|
|
167
|
+
|
|
145
168
|
### useSendTransactionX Hook
|
|
146
169
|
|
|
147
170
|
The `useSendTransactionX` hook wraps the transaction-sending functionality from Wagmi with additional features like `receipt` waiting, `logging` control, and `query invalidation` after receipt is successfully fetched.
|
package/dist/index.cjs.js
CHANGED
|
@@ -422,6 +422,9 @@ const useERC20ApproveX = (tokenAddress, spenderAddress, amount, approveMax) => {
|
|
|
422
422
|
});
|
|
423
423
|
const { writeContractAsync: approveTokenAsync, isPending } = useContractWriteX({
|
|
424
424
|
queriesToInvalidate: [allowanceKQ],
|
|
425
|
+
onSuccess: () => {
|
|
426
|
+
setJustApproved(true);
|
|
427
|
+
},
|
|
425
428
|
});
|
|
426
429
|
react.useEffect(() => {
|
|
427
430
|
if (amount == null) {
|
|
@@ -451,10 +454,6 @@ const useERC20ApproveX = (tokenAddress, spenderAddress, amount, approveMax) => {
|
|
|
451
454
|
abi: viem.erc20Abi,
|
|
452
455
|
functionName: "approve",
|
|
453
456
|
args: [spenderAddress, amountToApprove],
|
|
454
|
-
}, {
|
|
455
|
-
onSuccess: () => {
|
|
456
|
-
setJustApproved(true);
|
|
457
|
-
},
|
|
458
457
|
});
|
|
459
458
|
}
|
|
460
459
|
catch (e) {
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/utils/errorParserX.ts","../src/hooks/useInvalidateQueries.ts","../src/hooks/useHandleTransactionMutationX.ts","../src/hooks/useContractWriteX.ts","../src/hooks/useSendTransactionX.ts","../src/query-config/index.ts","../src/fetch-functions/fetchAllowanceX.ts","../src/hooks/useFetchAssetAllowanceX.ts","../src/hooks/useERC20ApproveX.ts","../src/config/defaults.ts","../src/fetch-functions/fetchTokenX.ts","../src/hooks/useTokenX.ts"],"sourcesContent":["import { BaseError, ContractFunctionRevertedError } from \"viem\";\n\n/**\n * Default error mapping that contains a set of error identifiers mapped to user-friendly error messages.\n */\nconst defaultErrorMapping: Record<string, string> = {\n EnforcedPause: \"Temporary pause in effect, please check Discord for updates.\",\n ErrorNotEnoughAllowance:\n \"Not enough allowance, did you approve your tokens first?\",\n \"0xc2139725\": \"Not enough allowance, did you approve your tokens first?\",\n SharesReceivedBelowMinimum:\n \"Action exceeded safe slippage parameters, please try again later\",\n \"0xea8d7f02\":\n \"Action exceeded safe slippage parameters, please try again later\",\n MaxSlippageExceeded:\n \"Action exceeded safe slippage parameters, please try again later\",\n \"51\": \"Supply cap exceeded\",\n};\n\n/**\n * A mutable copy of the default error mapping that can be extended or overridden by users.\n */\nlet currentErrorMapping: Record<string, string> = { ...defaultErrorMapping };\n\n/**\n * Merges a custom error mapping into the current error mapping.\n * Custom values override any existing keys.\n *\n * @param customMapping - An object containing error keys and the corresponding custom messages.\n *\n * @example\n * setErrorMapping({\n * ErrorNotEnoughAllowance: \"Custom message: Please approve tokens first!\",\n * NewCustomError: \"A custom error occurred.\"\n * });\n */\nexport const setErrorMapping = (\n customMapping: Record<string, string>\n): void => {\n currentErrorMapping = { ...currentErrorMapping, ...customMapping };\n};\n\n/**\n * Resets the current error mapping to the default error mapping.\n *\n * @example\n * resetErrorMapping();\n */\nexport const resetErrorMapping = (): void => {\n currentErrorMapping = {};\n};\n\n/**\n * Retrieves the current error mapping.\n *\n * @returns The current error mapping object.\n *\n * @example\n * const mapping = getErrorMapping();\n * console.log(mapping);\n */\nexport const getErrorMapping = (): Record<string, string> =>\n currentErrorMapping;\n\n/**\n * Parses an error object and returns a user-friendly error message.\n *\n * The function checks if the error is a ContractFunctionRevertedError by attempting to walk through\n * the error using its `walk` method. If a matching error is found and its error key exists in the\n * current error mapping, the corresponding custom message will be returned. Otherwise, it falls back\n * to the error's own message properties.\n *\n * @param error - The error object, potentially including additional error details.\n * @returns A user-friendly error message.\n *\n * @example\n * const message = getParsedError(someError);\n * console.log(message); // Outputs a custom error message or a default error message.\n */\nexport const getParsedErrorX = (error: any | BaseError): string => {\n const defaultMessage = \"An unknown error occurred. Please contact support.\";\n let message = defaultMessage;\n let errorKey = \"\";\n\n const revertedError = error?.walk\n ? error.walk((err: unknown) => err instanceof ContractFunctionRevertedError)\n : null;\n if (revertedError instanceof ContractFunctionRevertedError) {\n errorKey =\n revertedError.data?.errorName ??\n revertedError.signature ??\n revertedError.reason ??\n \"\";\n if (currentErrorMapping[errorKey]) return currentErrorMapping[errorKey];\n }\n\n message = error.shortMessage || error.details || error.message || message;\n return message;\n};\n","import { QueryKey, useQueryClient } from \"@tanstack/react-query\";\n\n/**\n * Hook to invalidate multiple queries in the React Query cache.\n *\n * @returns An object with the invalidateMany function.\n */\nexport function useInvalidateQueries() {\n const queryClient = useQueryClient();\n\n const invalidateMany = async (queries: (QueryKey | undefined)[]) => {\n const promises = queries.map((queryKey) =>\n queryClient.invalidateQueries({ queryKey })\n );\n await Promise.all(promises);\n };\n\n return { invalidateMany };\n}\n","import { waitForTransactionReceipt } from \"wagmi/actions\";\nimport { useConfig } from \"wagmi\";\nimport { QueryKey } from \"@tanstack/query-core\";\nimport { Address } from \"viem\";\nimport { useState } from \"react\";\nimport { getParsedErrorX } from \"../utils/errorParserX.js\";\nimport { useInvalidateQueries } from \"./useInvalidateQueries.js\";\n\nexport type WriteExtendedAsyncParams = {\n onSuccess?: (txHash: Address) => void;\n onError?: (e: any) => void;\n onSettled?: () => void;\n queriesToInvalidate?: (QueryKey | undefined)[];\n disableLogging?: boolean;\n disableWaitingForReceipt?: boolean;\n};\n\n/**\n * Custom hook to handle transaction mutations.\n *\n * @returns {Function} A shared `onSettled` callback for transaction mutations.\n */\nexport function useHandleTransactionMutationX({\n settings,\n}: {\n settings?: WriteExtendedAsyncParams;\n}) {\n const wagmiConfig = useConfig();\n\n const { invalidateMany } = useInvalidateQueries();\n const [isPending, setIsPending] = useState(false);\n const [errorMessage, setErrorMessage] = useState<string | undefined>(\n undefined\n );\n\n const onMutate = () => {\n setIsPending(true);\n setErrorMessage(undefined);\n };\n\n const onSettled = async (\n txHash: Address | undefined,\n error: any,\n args: any\n ) => {\n try {\n if (error) throw error;\n\n if (!settings?.disableWaitingForReceipt) {\n // 1. wait for transaction receipt\n const txReceipt = await waitForTransactionReceipt(wagmiConfig, {\n hash: txHash!,\n });\n\n // 2. throw if receipt is not valid\n if (txReceipt.status === \"reverted\")\n throw new Error(\"Execution reverted.\");\n if (txReceipt.status !== \"success\")\n throw new Error(\"Execution reverted.\");\n }\n\n // 3. invalidate queries\n if (settings?.queriesToInvalidate)\n await invalidateMany(settings?.queriesToInvalidate);\n\n // 4. call onSuccess callback\n settings?.onSuccess?.(txHash!);\n\n if (!settings?.disableLogging) {\n // 5. log result\n // eslint-disable-next-line no-console\n console.info(\"Operation successful:\", txHash); // todo: add logging service\n }\n // 6. return result\n return txHash;\n } catch (error) {\n const parsedError = getParsedErrorX(error);\n\n if (!settings?.disableLogging) {\n // 1. log error\n console.error(\n `ContractWriteExtended Operation failed with error(parsed): ${parsedError}`,\n { error },\n { args }\n );\n console.error({ error });\n }\n // 2. set error message\n setErrorMessage(parsedError);\n\n // 3. call callback\n settings?.onError?.(error);\n } finally {\n setIsPending(false);\n // 1. call callback\n settings?.onSettled?.();\n }\n return undefined;\n };\n\n return {\n onMutate,\n onSettled,\n isPending,\n errorMessage,\n };\n}\n","import { useWriteContract } from \"wagmi\";\nimport {\n WriteExtendedAsyncParams,\n useHandleTransactionMutationX,\n} from \"./useHandleTransactionMutationX.js\";\n\n/**\n * Custom hook for writing to a smart contract using Wagmi.\n *\n * 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.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.\n * @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.\n * @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.\n * @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.\n * @param {Function} [settings.onError] - Callback function to be called on transaction error.\n * @param {Function} [settings.onSettled] - Callback function to be called after the transaction settles (whether success or failure).\n * @param {QueryKey[]} [settings.queriesToInvalidate] - Array of query keys to invalidate after the transaction receives a receipt.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isPending - Indicates whether the transaction is pending.\n * - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.\n * - {Function} writeContractAsync - Function to trigger the write operation.\n * \n/**\n * Custom hook for writing a contract using Wagmi with extended functionality.\n *\n * This hook wraps Wagmi’s `useContractWriteX` with additional handling for\n * waiting for a transaction receipt, logging control, and invalidation of specified queries.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for handling the transaction.\n * @returns {Object} An object containing:\n * - `isPending`: {boolean} indicating if the transaction is in progress.\n * - `errorMessage`: {string|undefined} a potential error message.\n * - `writeContractAsync`: {Function} a function to trigger the transaction.\n *\n * @example\n * // In your component:\n * function MyTransactionComponent() {\n * const { writeContractAsync, isPending, errorMessage } = useContractWriteX({\n * queriesToInvalidate: [[\"userBalance\"], [\"userActivity\"]],\n * });\n *\n * const handleWrite = async () => {\n * try {\n * const txHash = await writeContractAsync({ transaction params here.. }, {\n * // use calbacks here in writeContractAsync or in useContractWriteX\n * onSuccess: (txHash) => console.log(\"Transaction successful:\", txHash),\n * onError: (error) => console.error(\"Transaction error:\", error),\n * });\n * console.log(\"Received txHash:\", txHash);\n * } catch (err) {\n * console.error(\"Failed writing transaction:\", err);`\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={handleWrite} disabled={isPending}>\n * {isPending ? \"Processing...\" : \"Write Transaction\"}\n * </button>\n * {errorMessage && <p>Error: {errorMessage}</p>}\n * </div>\n * );\n * }\n */\n\nexport function useContractWriteX(settings?: WriteExtendedAsyncParams) {\n const { isPending, errorMessage, onMutate, onSettled } =\n useHandleTransactionMutationX({\n settings,\n });\n\n const { writeContractAsync, ...rest } = useWriteContract({\n mutation: {\n onMutate,\n onSettled,\n },\n });\n\n return {\n ...rest,\n isPending,\n errorMessage,\n writeContractAsync,\n };\n}\n","import { useSendTransaction } from \"wagmi\";\nimport {\n useHandleTransactionMutationX,\n WriteExtendedAsyncParams,\n} from \"./useHandleTransactionMutationX.js\";\n\n/**\n * Custom hook for sending a transaction using Wagmi.\n *\n * 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.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.\n * @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.\n * @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.\n * @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.\n * @param {Function} [settings.onError] - Callback function to be called on transaction error.\n * @param {Function} [settings.onSettled] - Callback function to be called after the transaction settles (whether success or failure).\n * @param {QueryKey[]} [settings.queriesToInvalidate] - Array of query keys to invalidate after the transaction receives a receipt.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isPending - Indicates whether the transaction is pending.\n * - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.\n * - {Function} sendTransactionAsync - Function to trigger the send transaction mutation.\n\n * @example\n * // In your component:\n * function MyTransactionComponent() {\n * const { sendTransactionAsync, isPending, errorMessage } = useSendTransactionX({\n * // use calbacks here in useContractWriteX or in writeContractAsync\n * onSuccess: (txHash) => console.log(\"Transaction successful:\", txHash),\n * onError: (error) => console.error(\"Transaction error:\", error),\n * queriesToInvalidate: [[\"userBalance\"], [\"userActivity\"]],\n * });\n *\n * const handleSend = async () => {\n * try {\n * const txHash = await sendTransactionAsync({ transaction params here.. });\n * console.log(\"Received txHash:\", txHash);\n * } catch (err) {\n * console.error(\"Failed sending transaction:\", err);`\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={handleSend} disabled={isPending}>\n * {isPending ? \"Processing...\" : \"Send Transaction\"}\n * </button>\n * {errorMessage && <p>Error: {errorMessage}</p>}\n * </div>\n * );\n * }\n */\n\nexport function useSendTransactionX(settings?: WriteExtendedAsyncParams) {\n const { isPending, errorMessage, onMutate, onSettled } =\n useHandleTransactionMutationX({\n settings,\n });\n\n const { sendTransactionAsync, ...rest } = useSendTransaction({\n mutation: {\n onMutate,\n onSettled,\n },\n });\n\n return {\n ...rest,\n isPending,\n errorMessage,\n sendTransactionAsync,\n };\n}\n","export const queryConfig = {\n metadataQueryConfig: {\n staleTime: Infinity,\n },\n sensitiveDataQueryConfig: {\n staleTime: 60_000,\n },\n};\n","import { Address, erc20Abi } from \"viem\";\nimport { readContract } from \"viem/actions\";\n\nexport const fetchAllowance = async (\n asset: Address,\n spender: Address,\n userAddress: Address,\n config: any\n) => {\n const allowance = await readContract(config, {\n address: asset,\n abi: erc20Abi,\n functionName: \"allowance\",\n args: [userAddress, spender],\n });\n\n if (allowance == null) {\n throw new Error(\"Failed to fetch token data or allowance\");\n }\n\n return allowance;\n};\n","import { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { Address, erc20Abi } from \"viem\";\nimport { useAccount, useConfig } from \"wagmi\";\nimport { queryConfig } from \"../query-config/index.js\";\nimport { fetchAllowance } from \"../fetch-functions/fetchAllowanceX.js\";\n\nconst HookFetchAssetAllowanceQK = (\n asset?: Address,\n spender?: Address,\n userAddress?: Address\n) => [\"HookFetchAllowance\", asset, spender, userAddress] as const;\n\n/**\n * Custom hook for fetching asset allowance.\n *\n * @param {Address} asset - The address of the ERC20 token contract.\n * @param {Address} spender - The address of the spender to check allowance for.\n *\n *\n * @example\n * // In your component:\n * function AllowanceDisplay() {\n * const { data: allowance, isLoading, error } = useFetchAssetAllowanceX({\n * asset: \"0xTokenAddressExample\",\n * spender: \"0xSpenderAddressExample\",\n * });\n *\n * if (isLoading) return <div>Loading allowance...</div>;\n * if (error) return <div>Error loading allowance</div>;\n *\n * return (\n * <div>\n * Current Allowance: {allowance}\n * </div>\n * );\n * }\n */\nexport const useFetchAssetAllowanceX = ({\n asset,\n spender,\n}: {\n asset?: Address;\n spender?: Address;\n}) => {\n const config = useConfig();\n const { address: userAddress } = useAccount();\n\n const { data, ...rest } = useQuery({\n queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),\n queryFn: () => fetchAllowance(asset!, spender!, userAddress!, config),\n enabled: Boolean(asset) && Boolean(spender) && Boolean(userAddress),\n ...queryConfig.sensitiveDataQueryConfig,\n });\n\n return {\n ...rest,\n data,\n queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),\n };\n};\n","import { useState, useEffect } from \"react\";\nimport { Address, maxUint256, erc20Abi } from \"viem\";\nimport { useFetchAssetAllowanceX } from \"./useFetchAssetAllowanceX.js\";\nimport { useContractWriteX } from \"./useContractWriteX.js\";\n\n/**\n * Custom hook for approving ERC20 token transfers.\n *\n * This hook provides functionality for approving ERC20 token transfers, checking the current allowance, and handling the approval transaction using Wagmi.\n *\n * @param {Address} tokenAddress - The address of the ERC20 token contract (the transfer from).\n * @param {Address} spenderAddress - The address of the spender to approve the transfer to.\n * @param {bigint} [amount=BigInt(0)] - The amount to approve for transfer. Defaults to undefined.\n * @param {boolean} [approveMax=false] - Indicates whether to approve the maximum amount or a specific amount.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isApproved - Indicates whether the spender is already approved to transfer the specified amount of tokens.\n * - {boolean} isApproving - Indicates whether an approval transaction is currently pending.\n * - {Function} approveAsync - Function to trigger the approval transaction.\n *\n * @example\n * // In your component:\n * function ApproveTokenButton(amountToApprove) {\n * const tokenAddress = \"0xTokenAddressExample\";\n * const spenderAddress = \"0xSpenderAddressExample\";\n *\n * const { isApproved, isApproving, justApproved, approveAsync } = useERC20ApproveX(\n * tokenAddress,\n * spenderAddress,\n * parseUnits(amountToApprove.toString(), 18),\n * );\n *\n * return (\n * <button onClick={approveAsync} disabled={isApproving || isApproved}>\n * {isApproving ? \"Approving...\" : isApproved ? \"Approved\" : \"Approve Token\"}\n * </button>\n * );\n * }\n */\n\nexport const useERC20ApproveX = (\n tokenAddress?: Address,\n spenderAddress?: Address,\n amount?: bigint,\n approveMax?: boolean\n) => {\n const [isApproved, setIsApproved] = useState(false);\n const [justApproved, setJustApproved] = useState(false);\n\n const { data: allowance, queryKey: allowanceKQ } = useFetchAssetAllowanceX({\n asset: tokenAddress,\n spender: spenderAddress,\n });\n\n const { writeContractAsync: approveTokenAsync, isPending } =\n useContractWriteX({\n queriesToInvalidate: [allowanceKQ],\n });\n\n useEffect(() => {\n if (amount == null) {\n setIsApproved(false);\n } else if (allowance && allowance >= amount) {\n setIsApproved(true);\n } else {\n setIsApproved(false);\n }\n }, [allowance, amount]);\n\n const approveAsync = async () => {\n const amountToApprove = approveMax ? maxUint256 : amount;\n\n try {\n if (!spenderAddress) {\n throw new Error(\"spenderAddress is undefined!\");\n }\n if (!tokenAddress) {\n throw new Error(\"tokenAddress is undefined!\");\n }\n if (amountToApprove == null) {\n throw new Error(\"amountToApprove is undefined!\");\n }\n\n await approveTokenAsync(\n {\n address: tokenAddress,\n abi: erc20Abi,\n functionName: \"approve\",\n args: [spenderAddress, amountToApprove],\n },\n {\n onSuccess: () => {\n setJustApproved(true);\n },\n }\n );\n } catch (e: any) {\n console.error(\"Error approving token:\", e);\n throw e;\n }\n };\n\n return {\n isApproved,\n isApproving: isPending,\n justApproved,\n approveAsync,\n };\n};\n","// src/config/defaults.ts\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { Config } from \"wagmi\";\n\n// You can adjust the type for wagmiConfig to match your needs.\nlet defaultQueryClient: QueryClient | null = null;\nlet defaultWagmiConfig: any = null;\n\n/**\n * Sets the default configuration values.\n *\n * @param queryClient - The default QueryClient instance.\n * @param wagmiConfig - The default Wagmi configuration.\n * @example\n * //In your application initialization (e.g., index.tsx or App.tsx):\n * import { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\n * import { wagmiConfig } from \"/path/to/wagmi-config\";\n * import { setDefaults } from \"wagmi-extended\";\n *\n * const queryClient = new QueryClient();\n *\n * //Set defaults for the extended library functions.\n * setDefaults(queryClient, wagmiConfig);\n *\n * //Now helper functions like fetchTokenX can use these defaults if no explicit parameters are provided.\n */\nexport function setDefaults(\n queryClient: QueryClient,\n wagmiConfig: Config\n): void {\n defaultQueryClient = queryClient;\n defaultWagmiConfig = wagmiConfig;\n}\n\n/**\n * Retrieves the currently set default configurations.\n *\n * @throws Will throw an error if defaults are not initialized.\n * @returns An object containing the default queryClient and wagmiConfig.\n *\n * @example\n * // Usage in a helper function:\n * import { getDefaults } from \"wagmi-extended\";\n *\n * function exampleFunction() {\n * const { queryClient, wagmiConfig } = getDefaults();\n * // Use queryClient and wagmiConfig as needed...\n * }\n */\nexport function getDefaults(): {\n queryClient: QueryClient;\n wagmiConfig: Config;\n} {\n if (!defaultQueryClient || !defaultWagmiConfig) {\n throw new Error(\n \"Default configuration not set. Please call setDefaults() first.\"\n );\n }\n return { queryClient: defaultQueryClient, wagmiConfig: defaultWagmiConfig };\n}\n","import { QueryClient } from \"@tanstack/react-query\";\nimport { readContractQueryOptions } from \"wagmi/query\";\nimport { Address, zeroAddress, erc20Abi } from \"viem\";\nimport { Config } from \"wagmi\";\nimport { getDefaults } from \"../config/defaults.js\";\nimport { queryConfig } from \"../query-config/index.js\";\n\nexport interface Token {\n symbol: string;\n decimals: number;\n name: string;\n}\n\nexport const EthTokenData: Token = {\n symbol: \"ETH\",\n decimals: 18,\n name: \"Ethereum\",\n};\n\nexport async function fetchDecimalsX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<number | undefined> {\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n if (token === zeroAddress) return EthTokenData.decimals;\n\n const decimals = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"decimals\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return decimals;\n}\n\nexport async function fetchSymbolX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<string> {\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n if (token === zeroAddress) return EthTokenData.symbol;\n\n const symbol = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"symbol\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return symbol;\n}\n\nexport async function fetchNameX(\n token: Address,\n queryClient: any,\n wagmiConfig: any\n): Promise<string> {\n if (token === zeroAddress) return EthTokenData.name;\n\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n const name = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"name\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return name;\n}\n\n/**\n * Fetches the token metadata (symbol, decimals) for the given token address.\n * Internally calls:\n * - `fetchSymbol(token)` to retrieve the token symbol,\n * - `fetchDecimals(token)` to retrieve the token decimals\n * - `fetchName(token)` to retrieve the token name\n *\n * @param token - The address of the token.\n * @returns A `Token` object containing the symbol, decimals.\n * @throws Will throw an error if symbol or decimals cannot be fetched.\n */\nexport async function fetchTokenX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<Token> {\n const [symbol, decimals, name] = await Promise.all([\n fetchSymbolX(token, queryClient, wagmiConfig),\n fetchDecimalsX(token, queryClient, wagmiConfig),\n fetchNameX(token, queryClient, wagmiConfig),\n ]);\n if (!symbol || !decimals || !name) {\n throw new Error(\"Failed to fetch token data\");\n }\n\n return {\n symbol,\n decimals,\n name,\n };\n}\n","import { useQueryClient, useQuery } from \"@tanstack/react-query\";\nimport { Address } from \"viem\";\nimport { useConfig } from \"wagmi\";\nimport { fetchTokenX } from \"../fetch-functions/fetchTokenX.js\";\n\n/**\n * Returns a query key for fetching token data.\n *\n * @param {Address | undefined} asset - The token address.\n * @returns {Array} A unique query key for the token fetch.\n *\n * @example\n * const queryKey = HookFetchTokenQK(\"0x123...\");\n */\nexport const HookFetchTokenQK = (asset?: Address): any[] => [\n \"HookTokenWagmiExtended\",\n asset,\n];\n\n/**\n * Custom hook for fetching token metadata using extended Wagmi functionality.\n *\n * This hook leverages React Query for data fetching and caching.\n * It retrieves token metadata (such as symbol, decimals, name, etc.) for a given token address.\n *\n * @param {Address} [asset] - The token address.\n * @returns {Object} An object with the following properties:\n * - `data`: The token data (or undefined if not loaded).\n * - `isLoading`: Boolean indicating if the data is loading.\n * - `error`: Any error encountered during the fetch.\n * - `queryKey`: The unique key used for the query.\n *\n * @example\n * // In your component:\n * function MyTokenComponent() {\n * const { data, isLoading, error, queryKey } = useTokenX(\"0x123456...\");\n *\n * if (isLoading) return <div>Loading token data...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n *\n * return (\n * <div>\n * <p>Token Symbol: {data.symbol}</p>\n * <p>Decimals: {data.decimals}</p>\n * <p>Name: {data.name}</p>\n * </div>\n * );\n * }\n */\nexport const useTokenX = (asset?: Address) => {\n const queryClient = useQueryClient();\n const config = useConfig();\n\n const { data, ...rest } = useQuery({\n queryKey: HookFetchTokenQK(asset),\n queryFn: () => fetchTokenX(asset!, queryClient, config),\n enabled: Boolean(asset),\n });\n\n return {\n ...rest,\n data,\n queryKey: HookFetchTokenQK(asset),\n };\n};\n"],"names":["ContractFunctionRevertedError","useQueryClient","useConfig","useState","waitForTransactionReceipt","useWriteContract","useSendTransaction","readContract","erc20Abi","useAccount","useQuery","useEffect","maxUint256","zeroAddress","readContractQueryOptions"],"mappings":";;;;;;;;;;AAEA;;AAEG;AACH,MAAM,mBAAmB,GAA2B;AAClD,IAAA,aAAa,EAAE,8DAA8D;AAC7E,IAAA,uBAAuB,EACrB,0DAA0D;AAC5D,IAAA,YAAY,EAAE,0DAA0D;AACxE,IAAA,0BAA0B,EACxB,kEAAkE;AACpE,IAAA,YAAY,EACV,kEAAkE;AACpE,IAAA,mBAAmB,EACjB,kEAAkE;AACpE,IAAA,IAAI,EAAE,qBAAqB;CAC5B;AAED;;AAEG;AACH,IAAI,mBAAmB,GAA2B,EAAE,GAAG,mBAAmB,EAAE;AAE5E;;;;;;;;;;;AAWG;AACU,MAAA,eAAe,GAAG,CAC7B,aAAqC,KAC7B;IACR,mBAAmB,GAAG,EAAE,GAAG,mBAAmB,EAAE,GAAG,aAAa,EAAE;AACpE;AAEA;;;;;AAKG;AACI,MAAM,iBAAiB,GAAG,MAAW;IAC1C,mBAAmB,GAAG,EAAE;AAC1B;AAEA;;;;;;;;AAQG;MACU,eAAe,GAAG,MAC7B;AAEF;;;;;;;;;;;;;;AAcG;AACU,MAAA,eAAe,GAAG,CAAC,KAAsB,KAAY;;IAChE,MAAM,cAAc,GAAG,oDAAoD;IAC3E,IAAI,OAAO,GAAG,cAAc;IAC5B,IAAI,QAAQ,GAAG,EAAE;IAEjB,MAAM,aAAa,GAAG,CAAA,KAAK,aAAL,KAAK,KAAA,MAAA,GAAA,MAAA,GAAL,KAAK,CAAE,IAAI;AAC/B,UAAE,KAAK,CAAC,IAAI,CAAC,CAAC,GAAY,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AC,KAAM,EAAE,WAAW,EAAE,MAAM,CAAC;AACvD,QAAA,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC;AACxB,KAAA,CAAC;IAEF,OAAO;AACL,QAAA,GAAG,IAAI;QACP,IAAI;AACJ,QAAA,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC;KAClC;AACH;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/utils/errorParserX.ts","../src/hooks/useInvalidateQueries.ts","../src/hooks/useHandleTransactionMutationX.ts","../src/hooks/useContractWriteX.ts","../src/hooks/useSendTransactionX.ts","../src/query-config/index.ts","../src/fetch-functions/fetchAllowanceX.ts","../src/hooks/useFetchAssetAllowanceX.ts","../src/hooks/useERC20ApproveX.ts","../src/config/defaults.ts","../src/fetch-functions/fetchTokenX.ts","../src/hooks/useTokenX.ts"],"sourcesContent":["import { BaseError, ContractFunctionRevertedError } from \"viem\";\n\n/**\n * Default error mapping that contains a set of error identifiers mapped to user-friendly error messages.\n */\nconst defaultErrorMapping: Record<string, string> = {\n EnforcedPause: \"Temporary pause in effect, please check Discord for updates.\",\n ErrorNotEnoughAllowance:\n \"Not enough allowance, did you approve your tokens first?\",\n \"0xc2139725\": \"Not enough allowance, did you approve your tokens first?\",\n SharesReceivedBelowMinimum:\n \"Action exceeded safe slippage parameters, please try again later\",\n \"0xea8d7f02\":\n \"Action exceeded safe slippage parameters, please try again later\",\n MaxSlippageExceeded:\n \"Action exceeded safe slippage parameters, please try again later\",\n \"51\": \"Supply cap exceeded\",\n};\n\n/**\n * A mutable copy of the default error mapping that can be extended or overridden by users.\n */\nlet currentErrorMapping: Record<string, string> = { ...defaultErrorMapping };\n\n/**\n * Merges a custom error mapping into the current error mapping.\n * Custom values override any existing keys.\n *\n * @param customMapping - An object containing error keys and the corresponding custom messages.\n *\n * @example\n * setErrorMapping({\n * ErrorNotEnoughAllowance: \"Custom message: Please approve tokens first!\",\n * NewCustomError: \"A custom error occurred.\"\n * });\n */\nexport const setErrorMapping = (\n customMapping: Record<string, string>\n): void => {\n currentErrorMapping = { ...currentErrorMapping, ...customMapping };\n};\n\n/**\n * Resets the current error mapping to the default error mapping.\n *\n * @example\n * resetErrorMapping();\n */\nexport const resetErrorMapping = (): void => {\n currentErrorMapping = {};\n};\n\n/**\n * Retrieves the current error mapping.\n *\n * @returns The current error mapping object.\n *\n * @example\n * const mapping = getErrorMapping();\n * console.log(mapping);\n */\nexport const getErrorMapping = (): Record<string, string> =>\n currentErrorMapping;\n\n/**\n * Parses an error object and returns a user-friendly error message.\n *\n * The function checks if the error is a ContractFunctionRevertedError by attempting to walk through\n * the error using its `walk` method. If a matching error is found and its error key exists in the\n * current error mapping, the corresponding custom message will be returned. Otherwise, it falls back\n * to the error's own message properties.\n *\n * @param error - The error object, potentially including additional error details.\n * @returns A user-friendly error message.\n *\n * @example\n * const message = getParsedError(someError);\n * console.log(message); // Outputs a custom error message or a default error message.\n */\nexport const getParsedErrorX = (error: any | BaseError): string => {\n const defaultMessage = \"An unknown error occurred. Please contact support.\";\n let message = defaultMessage;\n let errorKey = \"\";\n\n const revertedError = error?.walk\n ? error.walk((err: unknown) => err instanceof ContractFunctionRevertedError)\n : null;\n if (revertedError instanceof ContractFunctionRevertedError) {\n errorKey =\n revertedError.data?.errorName ??\n revertedError.signature ??\n revertedError.reason ??\n \"\";\n if (currentErrorMapping[errorKey]) return currentErrorMapping[errorKey];\n }\n\n message = error.shortMessage || error.details || error.message || message;\n return message;\n};\n","import { QueryKey, useQueryClient } from \"@tanstack/react-query\";\n\n/**\n * Hook to invalidate multiple queries in the React Query cache.\n *\n * @returns An object with the invalidateMany function.\n */\nexport function useInvalidateQueries() {\n const queryClient = useQueryClient();\n\n const invalidateMany = async (queries: (QueryKey | undefined)[]) => {\n const promises = queries.map((queryKey) =>\n queryClient.invalidateQueries({ queryKey })\n );\n await Promise.all(promises);\n };\n\n return { invalidateMany };\n}\n","import { waitForTransactionReceipt } from \"wagmi/actions\";\nimport { useConfig } from \"wagmi\";\nimport { QueryKey } from \"@tanstack/query-core\";\nimport { Address } from \"viem\";\nimport { useState } from \"react\";\nimport { getParsedErrorX } from \"../utils/errorParserX.js\";\nimport { useInvalidateQueries } from \"./useInvalidateQueries.js\";\n\nexport type WriteExtendedAsyncParams = {\n onSuccess?: (txHash: Address) => void;\n onError?: (e: any) => void;\n onSettled?: () => void;\n queriesToInvalidate?: (QueryKey | undefined)[];\n disableLogging?: boolean;\n disableWaitingForReceipt?: boolean;\n};\n\n/**\n * Custom hook to handle transaction mutations.\n *\n * @returns {Function} A shared `onSettled` callback for transaction mutations.\n */\nexport function useHandleTransactionMutationX({\n settings,\n}: {\n settings?: WriteExtendedAsyncParams;\n}) {\n const wagmiConfig = useConfig();\n\n const { invalidateMany } = useInvalidateQueries();\n const [isPending, setIsPending] = useState(false);\n const [errorMessage, setErrorMessage] = useState<string | undefined>(\n undefined\n );\n\n const onMutate = () => {\n setIsPending(true);\n setErrorMessage(undefined);\n };\n\n const onSettled = async (\n txHash: Address | undefined,\n error: any,\n args: any\n ) => {\n try {\n if (error) throw error;\n\n if (!settings?.disableWaitingForReceipt) {\n // 1. wait for transaction receipt\n const txReceipt = await waitForTransactionReceipt(wagmiConfig, {\n hash: txHash!,\n });\n\n // 2. throw if receipt is not valid\n if (txReceipt.status === \"reverted\")\n throw new Error(\"Execution reverted.\");\n if (txReceipt.status !== \"success\")\n throw new Error(\"Execution reverted.\");\n }\n\n // 3. invalidate queries\n if (settings?.queriesToInvalidate)\n await invalidateMany(settings?.queriesToInvalidate);\n\n // 4. call onSuccess callback\n settings?.onSuccess?.(txHash!);\n\n if (!settings?.disableLogging) {\n // 5. log result\n // eslint-disable-next-line no-console\n console.info(\"Operation successful:\", txHash); // todo: add logging service\n }\n // 6. return result\n return txHash;\n } catch (error) {\n const parsedError = getParsedErrorX(error);\n\n if (!settings?.disableLogging) {\n // 1. log error\n console.error(\n `ContractWriteExtended Operation failed with error(parsed): ${parsedError}`,\n { error },\n { args }\n );\n console.error({ error });\n }\n // 2. set error message\n setErrorMessage(parsedError);\n\n // 3. call callback\n settings?.onError?.(error);\n } finally {\n setIsPending(false);\n // 1. call callback\n settings?.onSettled?.();\n }\n return undefined;\n };\n\n return {\n onMutate,\n onSettled,\n isPending,\n errorMessage,\n };\n}\n","import { useWriteContract } from \"wagmi\";\nimport {\n WriteExtendedAsyncParams,\n useHandleTransactionMutationX,\n} from \"./useHandleTransactionMutationX.js\";\n\n/**\n * Custom hook for writing to a smart contract using Wagmi.\n *\n * 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.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.\n * @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.\n * @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.\n * @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.\n * @param {Function} [settings.onError] - Callback function to be called on transaction error.\n * @param {Function} [settings.onSettled] - Callback function to be called after the transaction settles (whether success or failure).\n * @param {QueryKey[]} [settings.queriesToInvalidate] - Array of query keys to invalidate after the transaction receives a receipt.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isPending - Indicates whether the transaction is pending.\n * - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.\n * - {Function} writeContractAsync - Function to trigger the write operation.\n * \n/**\n * Custom hook for writing a contract using Wagmi with extended functionality.\n *\n * This hook wraps Wagmi’s `useContractWriteX` with additional handling for\n * waiting for a transaction receipt, logging control, and invalidation of specified queries.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for handling the transaction.\n * @returns {Object} An object containing:\n * - `isPending`: {boolean} indicating if the transaction is in progress.\n * - `errorMessage`: {string|undefined} a potential error message.\n * - `writeContractAsync`: {Function} a function to trigger the transaction.\n *\n * @example\n * // In your component:\n * function MyTransactionComponent() {\n * const { writeContractAsync, isPending, errorMessage } = useContractWriteX({\n * queriesToInvalidate: [[\"userBalance\"], [\"userActivity\"]],\n * });\n *\n * const handleWrite = async () => {\n * try {\n * const txHash = await writeContractAsync({ transaction params here.. }, {\n * // use calbacks here in writeContractAsync or in useContractWriteX\n * onSuccess: (txHash) => console.log(\"Transaction successful:\", txHash),\n * onError: (error) => console.error(\"Transaction error:\", error),\n * });\n * console.log(\"Received txHash:\", txHash);\n * } catch (err) {\n * console.error(\"Failed writing transaction:\", err);`\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={handleWrite} disabled={isPending}>\n * {isPending ? \"Processing...\" : \"Write Transaction\"}\n * </button>\n * {errorMessage && <p>Error: {errorMessage}</p>}\n * </div>\n * );\n * }\n */\n\nexport function useContractWriteX(settings?: WriteExtendedAsyncParams) {\n const { isPending, errorMessage, onMutate, onSettled } =\n useHandleTransactionMutationX({\n settings,\n });\n\n const { writeContractAsync, ...rest } = useWriteContract({\n mutation: {\n onMutate,\n onSettled,\n },\n });\n\n return {\n ...rest,\n isPending,\n errorMessage,\n writeContractAsync,\n };\n}\n","import { useSendTransaction } from \"wagmi\";\nimport {\n useHandleTransactionMutationX,\n WriteExtendedAsyncParams,\n} from \"./useHandleTransactionMutationX.js\";\n\n/**\n * Custom hook for sending a transaction using Wagmi.\n *\n * 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.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.\n * @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.\n * @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.\n * @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.\n * @param {Function} [settings.onError] - Callback function to be called on transaction error.\n * @param {Function} [settings.onSettled] - Callback function to be called after the transaction settles (whether success or failure).\n * @param {QueryKey[]} [settings.queriesToInvalidate] - Array of query keys to invalidate after the transaction receives a receipt.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isPending - Indicates whether the transaction is pending.\n * - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.\n * - {Function} sendTransactionAsync - Function to trigger the send transaction mutation.\n\n * @example\n * // In your component:\n * function MyTransactionComponent() {\n * const { sendTransactionAsync, isPending, errorMessage } = useSendTransactionX({\n * // use calbacks here in useContractWriteX or in writeContractAsync\n * onSuccess: (txHash) => console.log(\"Transaction successful:\", txHash),\n * onError: (error) => console.error(\"Transaction error:\", error),\n * queriesToInvalidate: [[\"userBalance\"], [\"userActivity\"]],\n * });\n *\n * const handleSend = async () => {\n * try {\n * const txHash = await sendTransactionAsync({ transaction params here.. });\n * console.log(\"Received txHash:\", txHash);\n * } catch (err) {\n * console.error(\"Failed sending transaction:\", err);`\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={handleSend} disabled={isPending}>\n * {isPending ? \"Processing...\" : \"Send Transaction\"}\n * </button>\n * {errorMessage && <p>Error: {errorMessage}</p>}\n * </div>\n * );\n * }\n */\n\nexport function useSendTransactionX(settings?: WriteExtendedAsyncParams) {\n const { isPending, errorMessage, onMutate, onSettled } =\n useHandleTransactionMutationX({\n settings,\n });\n\n const { sendTransactionAsync, ...rest } = useSendTransaction({\n mutation: {\n onMutate,\n onSettled,\n },\n });\n\n return {\n ...rest,\n isPending,\n errorMessage,\n sendTransactionAsync,\n };\n}\n","export const queryConfig = {\n metadataQueryConfig: {\n staleTime: Infinity,\n },\n sensitiveDataQueryConfig: {\n staleTime: 60_000,\n },\n};\n","import { Address, erc20Abi } from \"viem\";\nimport { readContract } from \"viem/actions\";\n\nexport const fetchAllowance = async (\n asset: Address,\n spender: Address,\n userAddress: Address,\n config: any\n) => {\n const allowance = await readContract(config, {\n address: asset,\n abi: erc20Abi,\n functionName: \"allowance\",\n args: [userAddress, spender],\n });\n\n if (allowance == null) {\n throw new Error(\"Failed to fetch token data or allowance\");\n }\n\n return allowance;\n};\n","import { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { Address, erc20Abi } from \"viem\";\nimport { useAccount, useConfig } from \"wagmi\";\nimport { queryConfig } from \"../query-config/index.js\";\nimport { fetchAllowance } from \"../fetch-functions/fetchAllowanceX.js\";\n\nconst HookFetchAssetAllowanceQK = (\n asset?: Address,\n spender?: Address,\n userAddress?: Address\n) => [\"HookFetchAllowance\", asset, spender, userAddress] as const;\n\n/**\n * Custom hook for fetching asset allowance.\n *\n * @param {Address} asset - The address of the ERC20 token contract.\n * @param {Address} spender - The address of the spender to check allowance for.\n *\n *\n * @example\n * // In your component:\n * function AllowanceDisplay() {\n * const { data: allowance, isLoading, error } = useFetchAssetAllowanceX({\n * asset: \"0xTokenAddressExample\",\n * spender: \"0xSpenderAddressExample\",\n * });\n *\n * if (isLoading) return <div>Loading allowance...</div>;\n * if (error) return <div>Error loading allowance</div>;\n *\n * return (\n * <div>\n * Current Allowance: {allowance}\n * </div>\n * );\n * }\n */\nexport const useFetchAssetAllowanceX = ({\n asset,\n spender,\n}: {\n asset?: Address;\n spender?: Address;\n}) => {\n const config = useConfig();\n const { address: userAddress } = useAccount();\n\n const { data, ...rest } = useQuery({\n queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),\n queryFn: () => fetchAllowance(asset!, spender!, userAddress!, config),\n enabled: Boolean(asset) && Boolean(spender) && Boolean(userAddress),\n ...queryConfig.sensitiveDataQueryConfig,\n });\n\n return {\n ...rest,\n data,\n queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),\n };\n};\n","import { useState, useEffect } from \"react\";\nimport { Address, maxUint256, erc20Abi } from \"viem\";\nimport { useFetchAssetAllowanceX } from \"./useFetchAssetAllowanceX.js\";\nimport { useContractWriteX } from \"./useContractWriteX.js\";\n\n/**\n * Custom hook for approving ERC20 token transfers.\n *\n * This hook provides functionality for approving ERC20 token transfers, checking the current allowance, and handling the approval transaction using Wagmi.\n *\n * @param {Address} tokenAddress - The address of the ERC20 token contract (the transfer from).\n * @param {Address} spenderAddress - The address of the spender to approve the transfer to.\n * @param {bigint} [amount=BigInt(0)] - The amount to approve for transfer. Defaults to undefined.\n * @param {boolean} [approveMax=false] - Indicates whether to approve the maximum amount or a specific amount.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isApproved - Indicates whether the spender is already approved to transfer the specified amount of tokens.\n * - {boolean} isApproving - Indicates whether an approval transaction is currently pending.\n * - {Function} approveAsync - Function to trigger the approval transaction.\n *\n * @example\n * // In your component:\n * function ApproveTokenButton(amountToApprove) {\n * const tokenAddress = \"0xTokenAddressExample\";\n * const spenderAddress = \"0xSpenderAddressExample\";\n *\n * const { isApproved, isApproving, justApproved, approveAsync } = useERC20ApproveX(\n * tokenAddress,\n * spenderAddress,\n * parseUnits(amountToApprove.toString(), 18),\n * );\n *\n * return (\n * <button onClick={approveAsync} disabled={isApproving || isApproved}>\n * {isApproving ? \"Approving...\" : isApproved ? \"Approved\" : \"Approve Token\"}\n * </button>\n * );\n * }\n */\n\nexport const useERC20ApproveX = (\n tokenAddress?: Address,\n spenderAddress?: Address,\n amount?: bigint,\n approveMax?: boolean\n) => {\n const [isApproved, setIsApproved] = useState(false);\n const [justApproved, setJustApproved] = useState(false);\n\n const { data: allowance, queryKey: allowanceKQ } = useFetchAssetAllowanceX({\n asset: tokenAddress,\n spender: spenderAddress,\n });\n\n const { writeContractAsync: approveTokenAsync, isPending } =\n useContractWriteX({\n queriesToInvalidate: [allowanceKQ],\n onSuccess: () => {\n setJustApproved(true);\n },\n });\n\n useEffect(() => {\n if (amount == null) {\n setIsApproved(false);\n } else if (allowance && allowance >= amount) {\n setIsApproved(true);\n } else {\n setIsApproved(false);\n }\n }, [allowance, amount]);\n\n const approveAsync = async () => {\n const amountToApprove = approveMax ? maxUint256 : amount;\n\n try {\n if (!spenderAddress) {\n throw new Error(\"spenderAddress is undefined!\");\n }\n if (!tokenAddress) {\n throw new Error(\"tokenAddress is undefined!\");\n }\n if (amountToApprove == null) {\n throw new Error(\"amountToApprove is undefined!\");\n }\n\n await approveTokenAsync({\n address: tokenAddress,\n abi: erc20Abi,\n functionName: \"approve\",\n args: [spenderAddress, amountToApprove],\n });\n } catch (e: any) {\n console.error(\"Error approving token:\", e);\n throw e;\n }\n };\n\n return {\n isApproved,\n isApproving: isPending,\n justApproved,\n approveAsync,\n };\n};\n","// src/config/defaults.ts\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { Config } from \"wagmi\";\n\n// You can adjust the type for wagmiConfig to match your needs.\nlet defaultQueryClient: QueryClient | null = null;\nlet defaultWagmiConfig: any = null;\n\n/**\n * Sets the default configuration values.\n *\n * @param queryClient - The default QueryClient instance.\n * @param wagmiConfig - The default Wagmi configuration.\n * @example\n * //In your application initialization (e.g., index.tsx or App.tsx):\n * import { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\n * import { wagmiConfig } from \"/path/to/wagmi-config\";\n * import { setDefaults } from \"wagmi-extended\";\n *\n * const queryClient = new QueryClient();\n *\n * //Set defaults for the extended library functions.\n * setDefaults(queryClient, wagmiConfig);\n *\n * //Now helper functions like fetchTokenX can use these defaults if no explicit parameters are provided.\n */\nexport function setDefaults(\n queryClient: QueryClient,\n wagmiConfig: Config\n): void {\n defaultQueryClient = queryClient;\n defaultWagmiConfig = wagmiConfig;\n}\n\n/**\n * Retrieves the currently set default configurations.\n *\n * @throws Will throw an error if defaults are not initialized.\n * @returns An object containing the default queryClient and wagmiConfig.\n *\n * @example\n * // Usage in a helper function:\n * import { getDefaults } from \"wagmi-extended\";\n *\n * function exampleFunction() {\n * const { queryClient, wagmiConfig } = getDefaults();\n * // Use queryClient and wagmiConfig as needed...\n * }\n */\nexport function getDefaults(): {\n queryClient: QueryClient;\n wagmiConfig: Config;\n} {\n if (!defaultQueryClient || !defaultWagmiConfig) {\n throw new Error(\n \"Default configuration not set. Please call setDefaults() first.\"\n );\n }\n return { queryClient: defaultQueryClient, wagmiConfig: defaultWagmiConfig };\n}\n","import { QueryClient } from \"@tanstack/react-query\";\nimport { readContractQueryOptions } from \"wagmi/query\";\nimport { Address, zeroAddress, erc20Abi } from \"viem\";\nimport { Config } from \"wagmi\";\nimport { getDefaults } from \"../config/defaults.js\";\nimport { queryConfig } from \"../query-config/index.js\";\n\nexport interface Token {\n symbol: string;\n decimals: number;\n name: string;\n}\n\nexport const EthTokenData: Token = {\n symbol: \"ETH\",\n decimals: 18,\n name: \"Ethereum\",\n};\n\nexport async function fetchDecimalsX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<number | undefined> {\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n if (token === zeroAddress) return EthTokenData.decimals;\n\n const decimals = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"decimals\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return decimals;\n}\n\nexport async function fetchSymbolX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<string> {\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n if (token === zeroAddress) return EthTokenData.symbol;\n\n const symbol = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"symbol\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return symbol;\n}\n\nexport async function fetchNameX(\n token: Address,\n queryClient: any,\n wagmiConfig: any\n): Promise<string> {\n if (token === zeroAddress) return EthTokenData.name;\n\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n const name = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"name\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return name;\n}\n\n/**\n * Fetches the token metadata (symbol, decimals) for the given token address.\n * Internally calls:\n * - `fetchSymbol(token)` to retrieve the token symbol,\n * - `fetchDecimals(token)` to retrieve the token decimals\n * - `fetchName(token)` to retrieve the token name\n *\n * @param token - The address of the token.\n * @returns A `Token` object containing the symbol, decimals.\n * @throws Will throw an error if symbol or decimals cannot be fetched.\n */\nexport async function fetchTokenX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<Token> {\n const [symbol, decimals, name] = await Promise.all([\n fetchSymbolX(token, queryClient, wagmiConfig),\n fetchDecimalsX(token, queryClient, wagmiConfig),\n fetchNameX(token, queryClient, wagmiConfig),\n ]);\n if (!symbol || !decimals || !name) {\n throw new Error(\"Failed to fetch token data\");\n }\n\n return {\n symbol,\n decimals,\n name,\n };\n}\n","import { useQueryClient, useQuery } from \"@tanstack/react-query\";\nimport { Address } from \"viem\";\nimport { useConfig } from \"wagmi\";\nimport { fetchTokenX } from \"../fetch-functions/fetchTokenX.js\";\n\n/**\n * Returns a query key for fetching token data.\n *\n * @param {Address | undefined} asset - The token address.\n * @returns {Array} A unique query key for the token fetch.\n *\n * @example\n * const queryKey = HookFetchTokenQK(\"0x123...\");\n */\nexport const HookFetchTokenQK = (asset?: Address): any[] => [\n \"HookTokenWagmiExtended\",\n asset,\n];\n\n/**\n * Custom hook for fetching token metadata using extended Wagmi functionality.\n *\n * This hook leverages React Query for data fetching and caching.\n * It retrieves token metadata (such as symbol, decimals, name, etc.) for a given token address.\n *\n * @param {Address} [asset] - The token address.\n * @returns {Object} An object with the following properties:\n * - `data`: The token data (or undefined if not loaded).\n * - `isLoading`: Boolean indicating if the data is loading.\n * - `error`: Any error encountered during the fetch.\n * - `queryKey`: The unique key used for the query.\n *\n * @example\n * // In your component:\n * function MyTokenComponent() {\n * const { data, isLoading, error, queryKey } = useTokenX(\"0x123456...\");\n *\n * if (isLoading) return <div>Loading token data...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n *\n * return (\n * <div>\n * <p>Token Symbol: {data.symbol}</p>\n * <p>Decimals: {data.decimals}</p>\n * <p>Name: {data.name}</p>\n * </div>\n * );\n * }\n */\nexport const useTokenX = (asset?: Address) => {\n const queryClient = useQueryClient();\n const config = useConfig();\n\n const { data, ...rest } = useQuery({\n queryKey: HookFetchTokenQK(asset),\n queryFn: () => fetchTokenX(asset!, queryClient, config),\n enabled: Boolean(asset),\n });\n\n return {\n ...rest,\n data,\n queryKey: HookFetchTokenQK(asset),\n };\n};\n"],"names":["ContractFunctionRevertedError","useQueryClient","useConfig","useState","waitForTransactionReceipt","useWriteContract","useSendTransaction","readContract","erc20Abi","useAccount","useQuery","useEffect","maxUint256","zeroAddress","readContractQueryOptions"],"mappings":";;;;;;;;;;AAEA;;AAEG;AACH,MAAM,mBAAmB,GAA2B;AAClD,IAAA,aAAa,EAAE,8DAA8D;AAC7E,IAAA,uBAAuB,EACrB,0DAA0D;AAC5D,IAAA,YAAY,EAAE,0DAA0D;AACxE,IAAA,0BAA0B,EACxB,kEAAkE;AACpE,IAAA,YAAY,EACV,kEAAkE;AACpE,IAAA,mBAAmB,EACjB,kEAAkE;AACpE,IAAA,IAAI,EAAE,qBAAqB;CAC5B;AAED;;AAEG;AACH,IAAI,mBAAmB,GAA2B,EAAE,GAAG,mBAAmB,EAAE;AAE5E;;;;;;;;;;;AAWG;AACU,MAAA,eAAe,GAAG,CAC7B,aAAqC,KAC7B;IACR,mBAAmB,GAAG,EAAE,GAAG,mBAAmB,EAAE,GAAG,aAAa,EAAE;AACpE;AAEA;;;;;AAKG;AACI,MAAM,iBAAiB,GAAG,MAAW;IAC1C,mBAAmB,GAAG,EAAE;AAC1B;AAEA;;;;;;;;AAQG;MACU,eAAe,GAAG,MAC7B;AAEF;;;;;;;;;;;;;;AAcG;AACU,MAAA,eAAe,GAAG,CAAC,KAAsB,KAAY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A,MAAM,WAAW,GAAGP,yBAAc,EAAE;AACpC,IAAA,MAAM,MAAM,GAAGC,eAAS,EAAE;IAE1B,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,GAAGQ,mBAAQ,CAAC;AACjC,QAAA,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC;QACjC,OAAO,EAAE,MAAM,WAAW,CAAC,KAAM,EAAE,WAAW,EAAE,MAAM,CAAC;AACvD,QAAA,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC;AACxB,KAAA,CAAC;IAEF,OAAO;AACL,QAAA,GAAG,IAAI;QACP,IAAI;AACJ,QAAA,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC;KAClC;AACH;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/index.esm.js
CHANGED
|
@@ -420,6 +420,9 @@ const useERC20ApproveX = (tokenAddress, spenderAddress, amount, approveMax) => {
|
|
|
420
420
|
});
|
|
421
421
|
const { writeContractAsync: approveTokenAsync, isPending } = useContractWriteX({
|
|
422
422
|
queriesToInvalidate: [allowanceKQ],
|
|
423
|
+
onSuccess: () => {
|
|
424
|
+
setJustApproved(true);
|
|
425
|
+
},
|
|
423
426
|
});
|
|
424
427
|
useEffect(() => {
|
|
425
428
|
if (amount == null) {
|
|
@@ -449,10 +452,6 @@ const useERC20ApproveX = (tokenAddress, spenderAddress, amount, approveMax) => {
|
|
|
449
452
|
abi: erc20Abi,
|
|
450
453
|
functionName: "approve",
|
|
451
454
|
args: [spenderAddress, amountToApprove],
|
|
452
|
-
}, {
|
|
453
|
-
onSuccess: () => {
|
|
454
|
-
setJustApproved(true);
|
|
455
|
-
},
|
|
456
455
|
});
|
|
457
456
|
}
|
|
458
457
|
catch (e) {
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/utils/errorParserX.ts","../src/hooks/useInvalidateQueries.ts","../src/hooks/useHandleTransactionMutationX.ts","../src/hooks/useContractWriteX.ts","../src/hooks/useSendTransactionX.ts","../src/query-config/index.ts","../src/fetch-functions/fetchAllowanceX.ts","../src/hooks/useFetchAssetAllowanceX.ts","../src/hooks/useERC20ApproveX.ts","../src/config/defaults.ts","../src/fetch-functions/fetchTokenX.ts","../src/hooks/useTokenX.ts"],"sourcesContent":["import { BaseError, ContractFunctionRevertedError } from \"viem\";\n\n/**\n * Default error mapping that contains a set of error identifiers mapped to user-friendly error messages.\n */\nconst defaultErrorMapping: Record<string, string> = {\n EnforcedPause: \"Temporary pause in effect, please check Discord for updates.\",\n ErrorNotEnoughAllowance:\n \"Not enough allowance, did you approve your tokens first?\",\n \"0xc2139725\": \"Not enough allowance, did you approve your tokens first?\",\n SharesReceivedBelowMinimum:\n \"Action exceeded safe slippage parameters, please try again later\",\n \"0xea8d7f02\":\n \"Action exceeded safe slippage parameters, please try again later\",\n MaxSlippageExceeded:\n \"Action exceeded safe slippage parameters, please try again later\",\n \"51\": \"Supply cap exceeded\",\n};\n\n/**\n * A mutable copy of the default error mapping that can be extended or overridden by users.\n */\nlet currentErrorMapping: Record<string, string> = { ...defaultErrorMapping };\n\n/**\n * Merges a custom error mapping into the current error mapping.\n * Custom values override any existing keys.\n *\n * @param customMapping - An object containing error keys and the corresponding custom messages.\n *\n * @example\n * setErrorMapping({\n * ErrorNotEnoughAllowance: \"Custom message: Please approve tokens first!\",\n * NewCustomError: \"A custom error occurred.\"\n * });\n */\nexport const setErrorMapping = (\n customMapping: Record<string, string>\n): void => {\n currentErrorMapping = { ...currentErrorMapping, ...customMapping };\n};\n\n/**\n * Resets the current error mapping to the default error mapping.\n *\n * @example\n * resetErrorMapping();\n */\nexport const resetErrorMapping = (): void => {\n currentErrorMapping = {};\n};\n\n/**\n * Retrieves the current error mapping.\n *\n * @returns The current error mapping object.\n *\n * @example\n * const mapping = getErrorMapping();\n * console.log(mapping);\n */\nexport const getErrorMapping = (): Record<string, string> =>\n currentErrorMapping;\n\n/**\n * Parses an error object and returns a user-friendly error message.\n *\n * The function checks if the error is a ContractFunctionRevertedError by attempting to walk through\n * the error using its `walk` method. If a matching error is found and its error key exists in the\n * current error mapping, the corresponding custom message will be returned. Otherwise, it falls back\n * to the error's own message properties.\n *\n * @param error - The error object, potentially including additional error details.\n * @returns A user-friendly error message.\n *\n * @example\n * const message = getParsedError(someError);\n * console.log(message); // Outputs a custom error message or a default error message.\n */\nexport const getParsedErrorX = (error: any | BaseError): string => {\n const defaultMessage = \"An unknown error occurred. Please contact support.\";\n let message = defaultMessage;\n let errorKey = \"\";\n\n const revertedError = error?.walk\n ? error.walk((err: unknown) => err instanceof ContractFunctionRevertedError)\n : null;\n if (revertedError instanceof ContractFunctionRevertedError) {\n errorKey =\n revertedError.data?.errorName ??\n revertedError.signature ??\n revertedError.reason ??\n \"\";\n if (currentErrorMapping[errorKey]) return currentErrorMapping[errorKey];\n }\n\n message = error.shortMessage || error.details || error.message || message;\n return message;\n};\n","import { QueryKey, useQueryClient } from \"@tanstack/react-query\";\n\n/**\n * Hook to invalidate multiple queries in the React Query cache.\n *\n * @returns An object with the invalidateMany function.\n */\nexport function useInvalidateQueries() {\n const queryClient = useQueryClient();\n\n const invalidateMany = async (queries: (QueryKey | undefined)[]) => {\n const promises = queries.map((queryKey) =>\n queryClient.invalidateQueries({ queryKey })\n );\n await Promise.all(promises);\n };\n\n return { invalidateMany };\n}\n","import { waitForTransactionReceipt } from \"wagmi/actions\";\nimport { useConfig } from \"wagmi\";\nimport { QueryKey } from \"@tanstack/query-core\";\nimport { Address } from \"viem\";\nimport { useState } from \"react\";\nimport { getParsedErrorX } from \"../utils/errorParserX.js\";\nimport { useInvalidateQueries } from \"./useInvalidateQueries.js\";\n\nexport type WriteExtendedAsyncParams = {\n onSuccess?: (txHash: Address) => void;\n onError?: (e: any) => void;\n onSettled?: () => void;\n queriesToInvalidate?: (QueryKey | undefined)[];\n disableLogging?: boolean;\n disableWaitingForReceipt?: boolean;\n};\n\n/**\n * Custom hook to handle transaction mutations.\n *\n * @returns {Function} A shared `onSettled` callback for transaction mutations.\n */\nexport function useHandleTransactionMutationX({\n settings,\n}: {\n settings?: WriteExtendedAsyncParams;\n}) {\n const wagmiConfig = useConfig();\n\n const { invalidateMany } = useInvalidateQueries();\n const [isPending, setIsPending] = useState(false);\n const [errorMessage, setErrorMessage] = useState<string | undefined>(\n undefined\n );\n\n const onMutate = () => {\n setIsPending(true);\n setErrorMessage(undefined);\n };\n\n const onSettled = async (\n txHash: Address | undefined,\n error: any,\n args: any\n ) => {\n try {\n if (error) throw error;\n\n if (!settings?.disableWaitingForReceipt) {\n // 1. wait for transaction receipt\n const txReceipt = await waitForTransactionReceipt(wagmiConfig, {\n hash: txHash!,\n });\n\n // 2. throw if receipt is not valid\n if (txReceipt.status === \"reverted\")\n throw new Error(\"Execution reverted.\");\n if (txReceipt.status !== \"success\")\n throw new Error(\"Execution reverted.\");\n }\n\n // 3. invalidate queries\n if (settings?.queriesToInvalidate)\n await invalidateMany(settings?.queriesToInvalidate);\n\n // 4. call onSuccess callback\n settings?.onSuccess?.(txHash!);\n\n if (!settings?.disableLogging) {\n // 5. log result\n // eslint-disable-next-line no-console\n console.info(\"Operation successful:\", txHash); // todo: add logging service\n }\n // 6. return result\n return txHash;\n } catch (error) {\n const parsedError = getParsedErrorX(error);\n\n if (!settings?.disableLogging) {\n // 1. log error\n console.error(\n `ContractWriteExtended Operation failed with error(parsed): ${parsedError}`,\n { error },\n { args }\n );\n console.error({ error });\n }\n // 2. set error message\n setErrorMessage(parsedError);\n\n // 3. call callback\n settings?.onError?.(error);\n } finally {\n setIsPending(false);\n // 1. call callback\n settings?.onSettled?.();\n }\n return undefined;\n };\n\n return {\n onMutate,\n onSettled,\n isPending,\n errorMessage,\n };\n}\n","import { useWriteContract } from \"wagmi\";\nimport {\n WriteExtendedAsyncParams,\n useHandleTransactionMutationX,\n} from \"./useHandleTransactionMutationX.js\";\n\n/**\n * Custom hook for writing to a smart contract using Wagmi.\n *\n * 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.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.\n * @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.\n * @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.\n * @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.\n * @param {Function} [settings.onError] - Callback function to be called on transaction error.\n * @param {Function} [settings.onSettled] - Callback function to be called after the transaction settles (whether success or failure).\n * @param {QueryKey[]} [settings.queriesToInvalidate] - Array of query keys to invalidate after the transaction receives a receipt.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isPending - Indicates whether the transaction is pending.\n * - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.\n * - {Function} writeContractAsync - Function to trigger the write operation.\n * \n/**\n * Custom hook for writing a contract using Wagmi with extended functionality.\n *\n * This hook wraps Wagmi’s `useContractWriteX` with additional handling for\n * waiting for a transaction receipt, logging control, and invalidation of specified queries.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for handling the transaction.\n * @returns {Object} An object containing:\n * - `isPending`: {boolean} indicating if the transaction is in progress.\n * - `errorMessage`: {string|undefined} a potential error message.\n * - `writeContractAsync`: {Function} a function to trigger the transaction.\n *\n * @example\n * // In your component:\n * function MyTransactionComponent() {\n * const { writeContractAsync, isPending, errorMessage } = useContractWriteX({\n * queriesToInvalidate: [[\"userBalance\"], [\"userActivity\"]],\n * });\n *\n * const handleWrite = async () => {\n * try {\n * const txHash = await writeContractAsync({ transaction params here.. }, {\n * // use calbacks here in writeContractAsync or in useContractWriteX\n * onSuccess: (txHash) => console.log(\"Transaction successful:\", txHash),\n * onError: (error) => console.error(\"Transaction error:\", error),\n * });\n * console.log(\"Received txHash:\", txHash);\n * } catch (err) {\n * console.error(\"Failed writing transaction:\", err);`\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={handleWrite} disabled={isPending}>\n * {isPending ? \"Processing...\" : \"Write Transaction\"}\n * </button>\n * {errorMessage && <p>Error: {errorMessage}</p>}\n * </div>\n * );\n * }\n */\n\nexport function useContractWriteX(settings?: WriteExtendedAsyncParams) {\n const { isPending, errorMessage, onMutate, onSettled } =\n useHandleTransactionMutationX({\n settings,\n });\n\n const { writeContractAsync, ...rest } = useWriteContract({\n mutation: {\n onMutate,\n onSettled,\n },\n });\n\n return {\n ...rest,\n isPending,\n errorMessage,\n writeContractAsync,\n };\n}\n","import { useSendTransaction } from \"wagmi\";\nimport {\n useHandleTransactionMutationX,\n WriteExtendedAsyncParams,\n} from \"./useHandleTransactionMutationX.js\";\n\n/**\n * Custom hook for sending a transaction using Wagmi.\n *\n * 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.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.\n * @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.\n * @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.\n * @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.\n * @param {Function} [settings.onError] - Callback function to be called on transaction error.\n * @param {Function} [settings.onSettled] - Callback function to be called after the transaction settles (whether success or failure).\n * @param {QueryKey[]} [settings.queriesToInvalidate] - Array of query keys to invalidate after the transaction receives a receipt.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isPending - Indicates whether the transaction is pending.\n * - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.\n * - {Function} sendTransactionAsync - Function to trigger the send transaction mutation.\n\n * @example\n * // In your component:\n * function MyTransactionComponent() {\n * const { sendTransactionAsync, isPending, errorMessage } = useSendTransactionX({\n * // use calbacks here in useContractWriteX or in writeContractAsync\n * onSuccess: (txHash) => console.log(\"Transaction successful:\", txHash),\n * onError: (error) => console.error(\"Transaction error:\", error),\n * queriesToInvalidate: [[\"userBalance\"], [\"userActivity\"]],\n * });\n *\n * const handleSend = async () => {\n * try {\n * const txHash = await sendTransactionAsync({ transaction params here.. });\n * console.log(\"Received txHash:\", txHash);\n * } catch (err) {\n * console.error(\"Failed sending transaction:\", err);`\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={handleSend} disabled={isPending}>\n * {isPending ? \"Processing...\" : \"Send Transaction\"}\n * </button>\n * {errorMessage && <p>Error: {errorMessage}</p>}\n * </div>\n * );\n * }\n */\n\nexport function useSendTransactionX(settings?: WriteExtendedAsyncParams) {\n const { isPending, errorMessage, onMutate, onSettled } =\n useHandleTransactionMutationX({\n settings,\n });\n\n const { sendTransactionAsync, ...rest } = useSendTransaction({\n mutation: {\n onMutate,\n onSettled,\n },\n });\n\n return {\n ...rest,\n isPending,\n errorMessage,\n sendTransactionAsync,\n };\n}\n","export const queryConfig = {\n metadataQueryConfig: {\n staleTime: Infinity,\n },\n sensitiveDataQueryConfig: {\n staleTime: 60_000,\n },\n};\n","import { Address, erc20Abi } from \"viem\";\nimport { readContract } from \"viem/actions\";\n\nexport const fetchAllowance = async (\n asset: Address,\n spender: Address,\n userAddress: Address,\n config: any\n) => {\n const allowance = await readContract(config, {\n address: asset,\n abi: erc20Abi,\n functionName: \"allowance\",\n args: [userAddress, spender],\n });\n\n if (allowance == null) {\n throw new Error(\"Failed to fetch token data or allowance\");\n }\n\n return allowance;\n};\n","import { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { Address, erc20Abi } from \"viem\";\nimport { useAccount, useConfig } from \"wagmi\";\nimport { queryConfig } from \"../query-config/index.js\";\nimport { fetchAllowance } from \"../fetch-functions/fetchAllowanceX.js\";\n\nconst HookFetchAssetAllowanceQK = (\n asset?: Address,\n spender?: Address,\n userAddress?: Address\n) => [\"HookFetchAllowance\", asset, spender, userAddress] as const;\n\n/**\n * Custom hook for fetching asset allowance.\n *\n * @param {Address} asset - The address of the ERC20 token contract.\n * @param {Address} spender - The address of the spender to check allowance for.\n *\n *\n * @example\n * // In your component:\n * function AllowanceDisplay() {\n * const { data: allowance, isLoading, error } = useFetchAssetAllowanceX({\n * asset: \"0xTokenAddressExample\",\n * spender: \"0xSpenderAddressExample\",\n * });\n *\n * if (isLoading) return <div>Loading allowance...</div>;\n * if (error) return <div>Error loading allowance</div>;\n *\n * return (\n * <div>\n * Current Allowance: {allowance}\n * </div>\n * );\n * }\n */\nexport const useFetchAssetAllowanceX = ({\n asset,\n spender,\n}: {\n asset?: Address;\n spender?: Address;\n}) => {\n const config = useConfig();\n const { address: userAddress } = useAccount();\n\n const { data, ...rest } = useQuery({\n queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),\n queryFn: () => fetchAllowance(asset!, spender!, userAddress!, config),\n enabled: Boolean(asset) && Boolean(spender) && Boolean(userAddress),\n ...queryConfig.sensitiveDataQueryConfig,\n });\n\n return {\n ...rest,\n data,\n queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),\n };\n};\n","import { useState, useEffect } from \"react\";\nimport { Address, maxUint256, erc20Abi } from \"viem\";\nimport { useFetchAssetAllowanceX } from \"./useFetchAssetAllowanceX.js\";\nimport { useContractWriteX } from \"./useContractWriteX.js\";\n\n/**\n * Custom hook for approving ERC20 token transfers.\n *\n * This hook provides functionality for approving ERC20 token transfers, checking the current allowance, and handling the approval transaction using Wagmi.\n *\n * @param {Address} tokenAddress - The address of the ERC20 token contract (the transfer from).\n * @param {Address} spenderAddress - The address of the spender to approve the transfer to.\n * @param {bigint} [amount=BigInt(0)] - The amount to approve for transfer. Defaults to undefined.\n * @param {boolean} [approveMax=false] - Indicates whether to approve the maximum amount or a specific amount.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isApproved - Indicates whether the spender is already approved to transfer the specified amount of tokens.\n * - {boolean} isApproving - Indicates whether an approval transaction is currently pending.\n * - {Function} approveAsync - Function to trigger the approval transaction.\n *\n * @example\n * // In your component:\n * function ApproveTokenButton(amountToApprove) {\n * const tokenAddress = \"0xTokenAddressExample\";\n * const spenderAddress = \"0xSpenderAddressExample\";\n *\n * const { isApproved, isApproving, justApproved, approveAsync } = useERC20ApproveX(\n * tokenAddress,\n * spenderAddress,\n * parseUnits(amountToApprove.toString(), 18),\n * );\n *\n * return (\n * <button onClick={approveAsync} disabled={isApproving || isApproved}>\n * {isApproving ? \"Approving...\" : isApproved ? \"Approved\" : \"Approve Token\"}\n * </button>\n * );\n * }\n */\n\nexport const useERC20ApproveX = (\n tokenAddress?: Address,\n spenderAddress?: Address,\n amount?: bigint,\n approveMax?: boolean\n) => {\n const [isApproved, setIsApproved] = useState(false);\n const [justApproved, setJustApproved] = useState(false);\n\n const { data: allowance, queryKey: allowanceKQ } = useFetchAssetAllowanceX({\n asset: tokenAddress,\n spender: spenderAddress,\n });\n\n const { writeContractAsync: approveTokenAsync, isPending } =\n useContractWriteX({\n queriesToInvalidate: [allowanceKQ],\n });\n\n useEffect(() => {\n if (amount == null) {\n setIsApproved(false);\n } else if (allowance && allowance >= amount) {\n setIsApproved(true);\n } else {\n setIsApproved(false);\n }\n }, [allowance, amount]);\n\n const approveAsync = async () => {\n const amountToApprove = approveMax ? maxUint256 : amount;\n\n try {\n if (!spenderAddress) {\n throw new Error(\"spenderAddress is undefined!\");\n }\n if (!tokenAddress) {\n throw new Error(\"tokenAddress is undefined!\");\n }\n if (amountToApprove == null) {\n throw new Error(\"amountToApprove is undefined!\");\n }\n\n await approveTokenAsync(\n {\n address: tokenAddress,\n abi: erc20Abi,\n functionName: \"approve\",\n args: [spenderAddress, amountToApprove],\n },\n {\n onSuccess: () => {\n setJustApproved(true);\n },\n }\n );\n } catch (e: any) {\n console.error(\"Error approving token:\", e);\n throw e;\n }\n };\n\n return {\n isApproved,\n isApproving: isPending,\n justApproved,\n approveAsync,\n };\n};\n","// src/config/defaults.ts\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { Config } from \"wagmi\";\n\n// You can adjust the type for wagmiConfig to match your needs.\nlet defaultQueryClient: QueryClient | null = null;\nlet defaultWagmiConfig: any = null;\n\n/**\n * Sets the default configuration values.\n *\n * @param queryClient - The default QueryClient instance.\n * @param wagmiConfig - The default Wagmi configuration.\n * @example\n * //In your application initialization (e.g., index.tsx or App.tsx):\n * import { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\n * import { wagmiConfig } from \"/path/to/wagmi-config\";\n * import { setDefaults } from \"wagmi-extended\";\n *\n * const queryClient = new QueryClient();\n *\n * //Set defaults for the extended library functions.\n * setDefaults(queryClient, wagmiConfig);\n *\n * //Now helper functions like fetchTokenX can use these defaults if no explicit parameters are provided.\n */\nexport function setDefaults(\n queryClient: QueryClient,\n wagmiConfig: Config\n): void {\n defaultQueryClient = queryClient;\n defaultWagmiConfig = wagmiConfig;\n}\n\n/**\n * Retrieves the currently set default configurations.\n *\n * @throws Will throw an error if defaults are not initialized.\n * @returns An object containing the default queryClient and wagmiConfig.\n *\n * @example\n * // Usage in a helper function:\n * import { getDefaults } from \"wagmi-extended\";\n *\n * function exampleFunction() {\n * const { queryClient, wagmiConfig } = getDefaults();\n * // Use queryClient and wagmiConfig as needed...\n * }\n */\nexport function getDefaults(): {\n queryClient: QueryClient;\n wagmiConfig: Config;\n} {\n if (!defaultQueryClient || !defaultWagmiConfig) {\n throw new Error(\n \"Default configuration not set. Please call setDefaults() first.\"\n );\n }\n return { queryClient: defaultQueryClient, wagmiConfig: defaultWagmiConfig };\n}\n","import { QueryClient } from \"@tanstack/react-query\";\nimport { readContractQueryOptions } from \"wagmi/query\";\nimport { Address, zeroAddress, erc20Abi } from \"viem\";\nimport { Config } from \"wagmi\";\nimport { getDefaults } from \"../config/defaults.js\";\nimport { queryConfig } from \"../query-config/index.js\";\n\nexport interface Token {\n symbol: string;\n decimals: number;\n name: string;\n}\n\nexport const EthTokenData: Token = {\n symbol: \"ETH\",\n decimals: 18,\n name: \"Ethereum\",\n};\n\nexport async function fetchDecimalsX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<number | undefined> {\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n if (token === zeroAddress) return EthTokenData.decimals;\n\n const decimals = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"decimals\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return decimals;\n}\n\nexport async function fetchSymbolX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<string> {\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n if (token === zeroAddress) return EthTokenData.symbol;\n\n const symbol = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"symbol\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return symbol;\n}\n\nexport async function fetchNameX(\n token: Address,\n queryClient: any,\n wagmiConfig: any\n): Promise<string> {\n if (token === zeroAddress) return EthTokenData.name;\n\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n const name = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"name\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return name;\n}\n\n/**\n * Fetches the token metadata (symbol, decimals) for the given token address.\n * Internally calls:\n * - `fetchSymbol(token)` to retrieve the token symbol,\n * - `fetchDecimals(token)` to retrieve the token decimals\n * - `fetchName(token)` to retrieve the token name\n *\n * @param token - The address of the token.\n * @returns A `Token` object containing the symbol, decimals.\n * @throws Will throw an error if symbol or decimals cannot be fetched.\n */\nexport async function fetchTokenX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<Token> {\n const [symbol, decimals, name] = await Promise.all([\n fetchSymbolX(token, queryClient, wagmiConfig),\n fetchDecimalsX(token, queryClient, wagmiConfig),\n fetchNameX(token, queryClient, wagmiConfig),\n ]);\n if (!symbol || !decimals || !name) {\n throw new Error(\"Failed to fetch token data\");\n }\n\n return {\n symbol,\n decimals,\n name,\n };\n}\n","import { useQueryClient, useQuery } from \"@tanstack/react-query\";\nimport { Address } from \"viem\";\nimport { useConfig } from \"wagmi\";\nimport { fetchTokenX } from \"../fetch-functions/fetchTokenX.js\";\n\n/**\n * Returns a query key for fetching token data.\n *\n * @param {Address | undefined} asset - The token address.\n * @returns {Array} A unique query key for the token fetch.\n *\n * @example\n * const queryKey = HookFetchTokenQK(\"0x123...\");\n */\nexport const HookFetchTokenQK = (asset?: Address): any[] => [\n \"HookTokenWagmiExtended\",\n asset,\n];\n\n/**\n * Custom hook for fetching token metadata using extended Wagmi functionality.\n *\n * This hook leverages React Query for data fetching and caching.\n * It retrieves token metadata (such as symbol, decimals, name, etc.) for a given token address.\n *\n * @param {Address} [asset] - The token address.\n * @returns {Object} An object with the following properties:\n * - `data`: The token data (or undefined if not loaded).\n * - `isLoading`: Boolean indicating if the data is loading.\n * - `error`: Any error encountered during the fetch.\n * - `queryKey`: The unique key used for the query.\n *\n * @example\n * // In your component:\n * function MyTokenComponent() {\n * const { data, isLoading, error, queryKey } = useTokenX(\"0x123456...\");\n *\n * if (isLoading) return <div>Loading token data...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n *\n * return (\n * <div>\n * <p>Token Symbol: {data.symbol}</p>\n * <p>Decimals: {data.decimals}</p>\n * <p>Name: {data.name}</p>\n * </div>\n * );\n * }\n */\nexport const useTokenX = (asset?: Address) => {\n const queryClient = useQueryClient();\n const config = useConfig();\n\n const { data, ...rest } = useQuery({\n queryKey: HookFetchTokenQK(asset),\n queryFn: () => fetchTokenX(asset!, queryClient, config),\n enabled: Boolean(asset),\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.ts","../src/hooks/useInvalidateQueries.ts","../src/hooks/useHandleTransactionMutationX.ts","../src/hooks/useContractWriteX.ts","../src/hooks/useSendTransactionX.ts","../src/query-config/index.ts","../src/fetch-functions/fetchAllowanceX.ts","../src/hooks/useFetchAssetAllowanceX.ts","../src/hooks/useERC20ApproveX.ts","../src/config/defaults.ts","../src/fetch-functions/fetchTokenX.ts","../src/hooks/useTokenX.ts"],"sourcesContent":["import { BaseError, ContractFunctionRevertedError } from \"viem\";\n\n/**\n * Default error mapping that contains a set of error identifiers mapped to user-friendly error messages.\n */\nconst defaultErrorMapping: Record<string, string> = {\n EnforcedPause: \"Temporary pause in effect, please check Discord for updates.\",\n ErrorNotEnoughAllowance:\n \"Not enough allowance, did you approve your tokens first?\",\n \"0xc2139725\": \"Not enough allowance, did you approve your tokens first?\",\n SharesReceivedBelowMinimum:\n \"Action exceeded safe slippage parameters, please try again later\",\n \"0xea8d7f02\":\n \"Action exceeded safe slippage parameters, please try again later\",\n MaxSlippageExceeded:\n \"Action exceeded safe slippage parameters, please try again later\",\n \"51\": \"Supply cap exceeded\",\n};\n\n/**\n * A mutable copy of the default error mapping that can be extended or overridden by users.\n */\nlet currentErrorMapping: Record<string, string> = { ...defaultErrorMapping };\n\n/**\n * Merges a custom error mapping into the current error mapping.\n * Custom values override any existing keys.\n *\n * @param customMapping - An object containing error keys and the corresponding custom messages.\n *\n * @example\n * setErrorMapping({\n * ErrorNotEnoughAllowance: \"Custom message: Please approve tokens first!\",\n * NewCustomError: \"A custom error occurred.\"\n * });\n */\nexport const setErrorMapping = (\n customMapping: Record<string, string>\n): void => {\n currentErrorMapping = { ...currentErrorMapping, ...customMapping };\n};\n\n/**\n * Resets the current error mapping to the default error mapping.\n *\n * @example\n * resetErrorMapping();\n */\nexport const resetErrorMapping = (): void => {\n currentErrorMapping = {};\n};\n\n/**\n * Retrieves the current error mapping.\n *\n * @returns The current error mapping object.\n *\n * @example\n * const mapping = getErrorMapping();\n * console.log(mapping);\n */\nexport const getErrorMapping = (): Record<string, string> =>\n currentErrorMapping;\n\n/**\n * Parses an error object and returns a user-friendly error message.\n *\n * The function checks if the error is a ContractFunctionRevertedError by attempting to walk through\n * the error using its `walk` method. If a matching error is found and its error key exists in the\n * current error mapping, the corresponding custom message will be returned. Otherwise, it falls back\n * to the error's own message properties.\n *\n * @param error - The error object, potentially including additional error details.\n * @returns A user-friendly error message.\n *\n * @example\n * const message = getParsedError(someError);\n * console.log(message); // Outputs a custom error message or a default error message.\n */\nexport const getParsedErrorX = (error: any | BaseError): string => {\n const defaultMessage = \"An unknown error occurred. Please contact support.\";\n let message = defaultMessage;\n let errorKey = \"\";\n\n const revertedError = error?.walk\n ? error.walk((err: unknown) => err instanceof ContractFunctionRevertedError)\n : null;\n if (revertedError instanceof ContractFunctionRevertedError) {\n errorKey =\n revertedError.data?.errorName ??\n revertedError.signature ??\n revertedError.reason ??\n \"\";\n if (currentErrorMapping[errorKey]) return currentErrorMapping[errorKey];\n }\n\n message = error.shortMessage || error.details || error.message || message;\n return message;\n};\n","import { QueryKey, useQueryClient } from \"@tanstack/react-query\";\n\n/**\n * Hook to invalidate multiple queries in the React Query cache.\n *\n * @returns An object with the invalidateMany function.\n */\nexport function useInvalidateQueries() {\n const queryClient = useQueryClient();\n\n const invalidateMany = async (queries: (QueryKey | undefined)[]) => {\n const promises = queries.map((queryKey) =>\n queryClient.invalidateQueries({ queryKey })\n );\n await Promise.all(promises);\n };\n\n return { invalidateMany };\n}\n","import { waitForTransactionReceipt } from \"wagmi/actions\";\nimport { useConfig } from \"wagmi\";\nimport { QueryKey } from \"@tanstack/query-core\";\nimport { Address } from \"viem\";\nimport { useState } from \"react\";\nimport { getParsedErrorX } from \"../utils/errorParserX.js\";\nimport { useInvalidateQueries } from \"./useInvalidateQueries.js\";\n\nexport type WriteExtendedAsyncParams = {\n onSuccess?: (txHash: Address) => void;\n onError?: (e: any) => void;\n onSettled?: () => void;\n queriesToInvalidate?: (QueryKey | undefined)[];\n disableLogging?: boolean;\n disableWaitingForReceipt?: boolean;\n};\n\n/**\n * Custom hook to handle transaction mutations.\n *\n * @returns {Function} A shared `onSettled` callback for transaction mutations.\n */\nexport function useHandleTransactionMutationX({\n settings,\n}: {\n settings?: WriteExtendedAsyncParams;\n}) {\n const wagmiConfig = useConfig();\n\n const { invalidateMany } = useInvalidateQueries();\n const [isPending, setIsPending] = useState(false);\n const [errorMessage, setErrorMessage] = useState<string | undefined>(\n undefined\n );\n\n const onMutate = () => {\n setIsPending(true);\n setErrorMessage(undefined);\n };\n\n const onSettled = async (\n txHash: Address | undefined,\n error: any,\n args: any\n ) => {\n try {\n if (error) throw error;\n\n if (!settings?.disableWaitingForReceipt) {\n // 1. wait for transaction receipt\n const txReceipt = await waitForTransactionReceipt(wagmiConfig, {\n hash: txHash!,\n });\n\n // 2. throw if receipt is not valid\n if (txReceipt.status === \"reverted\")\n throw new Error(\"Execution reverted.\");\n if (txReceipt.status !== \"success\")\n throw new Error(\"Execution reverted.\");\n }\n\n // 3. invalidate queries\n if (settings?.queriesToInvalidate)\n await invalidateMany(settings?.queriesToInvalidate);\n\n // 4. call onSuccess callback\n settings?.onSuccess?.(txHash!);\n\n if (!settings?.disableLogging) {\n // 5. log result\n // eslint-disable-next-line no-console\n console.info(\"Operation successful:\", txHash); // todo: add logging service\n }\n // 6. return result\n return txHash;\n } catch (error) {\n const parsedError = getParsedErrorX(error);\n\n if (!settings?.disableLogging) {\n // 1. log error\n console.error(\n `ContractWriteExtended Operation failed with error(parsed): ${parsedError}`,\n { error },\n { args }\n );\n console.error({ error });\n }\n // 2. set error message\n setErrorMessage(parsedError);\n\n // 3. call callback\n settings?.onError?.(error);\n } finally {\n setIsPending(false);\n // 1. call callback\n settings?.onSettled?.();\n }\n return undefined;\n };\n\n return {\n onMutate,\n onSettled,\n isPending,\n errorMessage,\n };\n}\n","import { useWriteContract } from \"wagmi\";\nimport {\n WriteExtendedAsyncParams,\n useHandleTransactionMutationX,\n} from \"./useHandleTransactionMutationX.js\";\n\n/**\n * Custom hook for writing to a smart contract using Wagmi.\n *\n * 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.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.\n * @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.\n * @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.\n * @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.\n * @param {Function} [settings.onError] - Callback function to be called on transaction error.\n * @param {Function} [settings.onSettled] - Callback function to be called after the transaction settles (whether success or failure).\n * @param {QueryKey[]} [settings.queriesToInvalidate] - Array of query keys to invalidate after the transaction receives a receipt.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isPending - Indicates whether the transaction is pending.\n * - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.\n * - {Function} writeContractAsync - Function to trigger the write operation.\n * \n/**\n * Custom hook for writing a contract using Wagmi with extended functionality.\n *\n * This hook wraps Wagmi’s `useContractWriteX` with additional handling for\n * waiting for a transaction receipt, logging control, and invalidation of specified queries.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for handling the transaction.\n * @returns {Object} An object containing:\n * - `isPending`: {boolean} indicating if the transaction is in progress.\n * - `errorMessage`: {string|undefined} a potential error message.\n * - `writeContractAsync`: {Function} a function to trigger the transaction.\n *\n * @example\n * // In your component:\n * function MyTransactionComponent() {\n * const { writeContractAsync, isPending, errorMessage } = useContractWriteX({\n * queriesToInvalidate: [[\"userBalance\"], [\"userActivity\"]],\n * });\n *\n * const handleWrite = async () => {\n * try {\n * const txHash = await writeContractAsync({ transaction params here.. }, {\n * // use calbacks here in writeContractAsync or in useContractWriteX\n * onSuccess: (txHash) => console.log(\"Transaction successful:\", txHash),\n * onError: (error) => console.error(\"Transaction error:\", error),\n * });\n * console.log(\"Received txHash:\", txHash);\n * } catch (err) {\n * console.error(\"Failed writing transaction:\", err);`\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={handleWrite} disabled={isPending}>\n * {isPending ? \"Processing...\" : \"Write Transaction\"}\n * </button>\n * {errorMessage && <p>Error: {errorMessage}</p>}\n * </div>\n * );\n * }\n */\n\nexport function useContractWriteX(settings?: WriteExtendedAsyncParams) {\n const { isPending, errorMessage, onMutate, onSettled } =\n useHandleTransactionMutationX({\n settings,\n });\n\n const { writeContractAsync, ...rest } = useWriteContract({\n mutation: {\n onMutate,\n onSettled,\n },\n });\n\n return {\n ...rest,\n isPending,\n errorMessage,\n writeContractAsync,\n };\n}\n","import { useSendTransaction } from \"wagmi\";\nimport {\n useHandleTransactionMutationX,\n WriteExtendedAsyncParams,\n} from \"./useHandleTransactionMutationX.js\";\n\n/**\n * Custom hook for sending a transaction using Wagmi.\n *\n * 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.\n *\n * @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.\n * @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.\n * @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.\n * @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.\n * @param {Function} [settings.onError] - Callback function to be called on transaction error.\n * @param {Function} [settings.onSettled] - Callback function to be called after the transaction settles (whether success or failure).\n * @param {QueryKey[]} [settings.queriesToInvalidate] - Array of query keys to invalidate after the transaction receives a receipt.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isPending - Indicates whether the transaction is pending.\n * - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.\n * - {Function} sendTransactionAsync - Function to trigger the send transaction mutation.\n\n * @example\n * // In your component:\n * function MyTransactionComponent() {\n * const { sendTransactionAsync, isPending, errorMessage } = useSendTransactionX({\n * // use calbacks here in useContractWriteX or in writeContractAsync\n * onSuccess: (txHash) => console.log(\"Transaction successful:\", txHash),\n * onError: (error) => console.error(\"Transaction error:\", error),\n * queriesToInvalidate: [[\"userBalance\"], [\"userActivity\"]],\n * });\n *\n * const handleSend = async () => {\n * try {\n * const txHash = await sendTransactionAsync({ transaction params here.. });\n * console.log(\"Received txHash:\", txHash);\n * } catch (err) {\n * console.error(\"Failed sending transaction:\", err);`\n * }\n * };\n *\n * return (\n * <div>\n * <button onClick={handleSend} disabled={isPending}>\n * {isPending ? \"Processing...\" : \"Send Transaction\"}\n * </button>\n * {errorMessage && <p>Error: {errorMessage}</p>}\n * </div>\n * );\n * }\n */\n\nexport function useSendTransactionX(settings?: WriteExtendedAsyncParams) {\n const { isPending, errorMessage, onMutate, onSettled } =\n useHandleTransactionMutationX({\n settings,\n });\n\n const { sendTransactionAsync, ...rest } = useSendTransaction({\n mutation: {\n onMutate,\n onSettled,\n },\n });\n\n return {\n ...rest,\n isPending,\n errorMessage,\n sendTransactionAsync,\n };\n}\n","export const queryConfig = {\n metadataQueryConfig: {\n staleTime: Infinity,\n },\n sensitiveDataQueryConfig: {\n staleTime: 60_000,\n },\n};\n","import { Address, erc20Abi } from \"viem\";\nimport { readContract } from \"viem/actions\";\n\nexport const fetchAllowance = async (\n asset: Address,\n spender: Address,\n userAddress: Address,\n config: any\n) => {\n const allowance = await readContract(config, {\n address: asset,\n abi: erc20Abi,\n functionName: \"allowance\",\n args: [userAddress, spender],\n });\n\n if (allowance == null) {\n throw new Error(\"Failed to fetch token data or allowance\");\n }\n\n return allowance;\n};\n","import { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { Address, erc20Abi } from \"viem\";\nimport { useAccount, useConfig } from \"wagmi\";\nimport { queryConfig } from \"../query-config/index.js\";\nimport { fetchAllowance } from \"../fetch-functions/fetchAllowanceX.js\";\n\nconst HookFetchAssetAllowanceQK = (\n asset?: Address,\n spender?: Address,\n userAddress?: Address\n) => [\"HookFetchAllowance\", asset, spender, userAddress] as const;\n\n/**\n * Custom hook for fetching asset allowance.\n *\n * @param {Address} asset - The address of the ERC20 token contract.\n * @param {Address} spender - The address of the spender to check allowance for.\n *\n *\n * @example\n * // In your component:\n * function AllowanceDisplay() {\n * const { data: allowance, isLoading, error } = useFetchAssetAllowanceX({\n * asset: \"0xTokenAddressExample\",\n * spender: \"0xSpenderAddressExample\",\n * });\n *\n * if (isLoading) return <div>Loading allowance...</div>;\n * if (error) return <div>Error loading allowance</div>;\n *\n * return (\n * <div>\n * Current Allowance: {allowance}\n * </div>\n * );\n * }\n */\nexport const useFetchAssetAllowanceX = ({\n asset,\n spender,\n}: {\n asset?: Address;\n spender?: Address;\n}) => {\n const config = useConfig();\n const { address: userAddress } = useAccount();\n\n const { data, ...rest } = useQuery({\n queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),\n queryFn: () => fetchAllowance(asset!, spender!, userAddress!, config),\n enabled: Boolean(asset) && Boolean(spender) && Boolean(userAddress),\n ...queryConfig.sensitiveDataQueryConfig,\n });\n\n return {\n ...rest,\n data,\n queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),\n };\n};\n","import { useState, useEffect } from \"react\";\nimport { Address, maxUint256, erc20Abi } from \"viem\";\nimport { useFetchAssetAllowanceX } from \"./useFetchAssetAllowanceX.js\";\nimport { useContractWriteX } from \"./useContractWriteX.js\";\n\n/**\n * Custom hook for approving ERC20 token transfers.\n *\n * This hook provides functionality for approving ERC20 token transfers, checking the current allowance, and handling the approval transaction using Wagmi.\n *\n * @param {Address} tokenAddress - The address of the ERC20 token contract (the transfer from).\n * @param {Address} spenderAddress - The address of the spender to approve the transfer to.\n * @param {bigint} [amount=BigInt(0)] - The amount to approve for transfer. Defaults to undefined.\n * @param {boolean} [approveMax=false] - Indicates whether to approve the maximum amount or a specific amount.\n * @returns {Object} Object containing the following properties:\n * - {boolean} isApproved - Indicates whether the spender is already approved to transfer the specified amount of tokens.\n * - {boolean} isApproving - Indicates whether an approval transaction is currently pending.\n * - {Function} approveAsync - Function to trigger the approval transaction.\n *\n * @example\n * // In your component:\n * function ApproveTokenButton(amountToApprove) {\n * const tokenAddress = \"0xTokenAddressExample\";\n * const spenderAddress = \"0xSpenderAddressExample\";\n *\n * const { isApproved, isApproving, justApproved, approveAsync } = useERC20ApproveX(\n * tokenAddress,\n * spenderAddress,\n * parseUnits(amountToApprove.toString(), 18),\n * );\n *\n * return (\n * <button onClick={approveAsync} disabled={isApproving || isApproved}>\n * {isApproving ? \"Approving...\" : isApproved ? \"Approved\" : \"Approve Token\"}\n * </button>\n * );\n * }\n */\n\nexport const useERC20ApproveX = (\n tokenAddress?: Address,\n spenderAddress?: Address,\n amount?: bigint,\n approveMax?: boolean\n) => {\n const [isApproved, setIsApproved] = useState(false);\n const [justApproved, setJustApproved] = useState(false);\n\n const { data: allowance, queryKey: allowanceKQ } = useFetchAssetAllowanceX({\n asset: tokenAddress,\n spender: spenderAddress,\n });\n\n const { writeContractAsync: approveTokenAsync, isPending } =\n useContractWriteX({\n queriesToInvalidate: [allowanceKQ],\n onSuccess: () => {\n setJustApproved(true);\n },\n });\n\n useEffect(() => {\n if (amount == null) {\n setIsApproved(false);\n } else if (allowance && allowance >= amount) {\n setIsApproved(true);\n } else {\n setIsApproved(false);\n }\n }, [allowance, amount]);\n\n const approveAsync = async () => {\n const amountToApprove = approveMax ? maxUint256 : amount;\n\n try {\n if (!spenderAddress) {\n throw new Error(\"spenderAddress is undefined!\");\n }\n if (!tokenAddress) {\n throw new Error(\"tokenAddress is undefined!\");\n }\n if (amountToApprove == null) {\n throw new Error(\"amountToApprove is undefined!\");\n }\n\n await approveTokenAsync({\n address: tokenAddress,\n abi: erc20Abi,\n functionName: \"approve\",\n args: [spenderAddress, amountToApprove],\n });\n } catch (e: any) {\n console.error(\"Error approving token:\", e);\n throw e;\n }\n };\n\n return {\n isApproved,\n isApproving: isPending,\n justApproved,\n approveAsync,\n };\n};\n","// src/config/defaults.ts\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { Config } from \"wagmi\";\n\n// You can adjust the type for wagmiConfig to match your needs.\nlet defaultQueryClient: QueryClient | null = null;\nlet defaultWagmiConfig: any = null;\n\n/**\n * Sets the default configuration values.\n *\n * @param queryClient - The default QueryClient instance.\n * @param wagmiConfig - The default Wagmi configuration.\n * @example\n * //In your application initialization (e.g., index.tsx or App.tsx):\n * import { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\n * import { wagmiConfig } from \"/path/to/wagmi-config\";\n * import { setDefaults } from \"wagmi-extended\";\n *\n * const queryClient = new QueryClient();\n *\n * //Set defaults for the extended library functions.\n * setDefaults(queryClient, wagmiConfig);\n *\n * //Now helper functions like fetchTokenX can use these defaults if no explicit parameters are provided.\n */\nexport function setDefaults(\n queryClient: QueryClient,\n wagmiConfig: Config\n): void {\n defaultQueryClient = queryClient;\n defaultWagmiConfig = wagmiConfig;\n}\n\n/**\n * Retrieves the currently set default configurations.\n *\n * @throws Will throw an error if defaults are not initialized.\n * @returns An object containing the default queryClient and wagmiConfig.\n *\n * @example\n * // Usage in a helper function:\n * import { getDefaults } from \"wagmi-extended\";\n *\n * function exampleFunction() {\n * const { queryClient, wagmiConfig } = getDefaults();\n * // Use queryClient and wagmiConfig as needed...\n * }\n */\nexport function getDefaults(): {\n queryClient: QueryClient;\n wagmiConfig: Config;\n} {\n if (!defaultQueryClient || !defaultWagmiConfig) {\n throw new Error(\n \"Default configuration not set. Please call setDefaults() first.\"\n );\n }\n return { queryClient: defaultQueryClient, wagmiConfig: defaultWagmiConfig };\n}\n","import { QueryClient } from \"@tanstack/react-query\";\nimport { readContractQueryOptions } from \"wagmi/query\";\nimport { Address, zeroAddress, erc20Abi } from \"viem\";\nimport { Config } from \"wagmi\";\nimport { getDefaults } from \"../config/defaults.js\";\nimport { queryConfig } from \"../query-config/index.js\";\n\nexport interface Token {\n symbol: string;\n decimals: number;\n name: string;\n}\n\nexport const EthTokenData: Token = {\n symbol: \"ETH\",\n decimals: 18,\n name: \"Ethereum\",\n};\n\nexport async function fetchDecimalsX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<number | undefined> {\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n if (token === zeroAddress) return EthTokenData.decimals;\n\n const decimals = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"decimals\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return decimals;\n}\n\nexport async function fetchSymbolX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<string> {\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n if (token === zeroAddress) return EthTokenData.symbol;\n\n const symbol = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"symbol\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return symbol;\n}\n\nexport async function fetchNameX(\n token: Address,\n queryClient: any,\n wagmiConfig: any\n): Promise<string> {\n if (token === zeroAddress) return EthTokenData.name;\n\n if (!queryClient || !wagmiConfig) {\n ({ queryClient, wagmiConfig } = getDefaults());\n }\n if (!queryClient || !wagmiConfig) {\n throw new Error(\n \"Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()\"\n );\n }\n\n const name = await queryClient.fetchQuery({\n ...readContractQueryOptions(wagmiConfig, {\n address: token,\n abi: erc20Abi,\n functionName: \"name\",\n }),\n ...queryConfig.metadataQueryConfig,\n });\n\n return name;\n}\n\n/**\n * Fetches the token metadata (symbol, decimals) for the given token address.\n * Internally calls:\n * - `fetchSymbol(token)` to retrieve the token symbol,\n * - `fetchDecimals(token)` to retrieve the token decimals\n * - `fetchName(token)` to retrieve the token name\n *\n * @param token - The address of the token.\n * @returns A `Token` object containing the symbol, decimals.\n * @throws Will throw an error if symbol or decimals cannot be fetched.\n */\nexport async function fetchTokenX(\n token: Address,\n queryClient?: QueryClient,\n wagmiConfig?: Config\n): Promise<Token> {\n const [symbol, decimals, name] = await Promise.all([\n fetchSymbolX(token, queryClient, wagmiConfig),\n fetchDecimalsX(token, queryClient, wagmiConfig),\n fetchNameX(token, queryClient, wagmiConfig),\n ]);\n if (!symbol || !decimals || !name) {\n throw new Error(\"Failed to fetch token data\");\n }\n\n return {\n symbol,\n decimals,\n name,\n };\n}\n","import { useQueryClient, useQuery } from \"@tanstack/react-query\";\nimport { Address } from \"viem\";\nimport { useConfig } from \"wagmi\";\nimport { fetchTokenX } from \"../fetch-functions/fetchTokenX.js\";\n\n/**\n * Returns a query key for fetching token data.\n *\n * @param {Address | undefined} asset - The token address.\n * @returns {Array} A unique query key for the token fetch.\n *\n * @example\n * const queryKey = HookFetchTokenQK(\"0x123...\");\n */\nexport const HookFetchTokenQK = (asset?: Address): any[] => [\n \"HookTokenWagmiExtended\",\n asset,\n];\n\n/**\n * Custom hook for fetching token metadata using extended Wagmi functionality.\n *\n * This hook leverages React Query for data fetching and caching.\n * It retrieves token metadata (such as symbol, decimals, name, etc.) for a given token address.\n *\n * @param {Address} [asset] - The token address.\n * @returns {Object} An object with the following properties:\n * - `data`: The token data (or undefined if not loaded).\n * - `isLoading`: Boolean indicating if the data is loading.\n * - `error`: Any error encountered during the fetch.\n * - `queryKey`: The unique key used for the query.\n *\n * @example\n * // In your component:\n * function MyTokenComponent() {\n * const { data, isLoading, error, queryKey } = useTokenX(\"0x123456...\");\n *\n * if (isLoading) return <div>Loading token data...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n *\n * return (\n * <div>\n * <p>Token Symbol: {data.symbol}</p>\n * <p>Decimals: {data.decimals}</p>\n * <p>Name: {data.name}</p>\n * </div>\n * );\n * }\n */\nexport const useTokenX = (asset?: Address) => {\n const queryClient = useQueryClient();\n const config = useConfig();\n\n const { data, ...rest } = useQuery({\n queryKey: HookFetchTokenQK(asset),\n queryFn: () => fetchTokenX(asset!, queryClient, config),\n enabled: Boolean(asset),\n });\n\n return {\n ...rest,\n data,\n queryKey: HookFetchTokenQK(asset),\n };\n};\n"],"names":[],"mappings":";;;;;;;;AAEA;;AAEG;AACH,MAAM,mBAAmB,GAA2B;AAClD,IAAA,aAAa,EAAE,8DAA8D;AAC7E,IAAA,uBAAuB,EACrB,0DAA0D;AAC5D,IAAA,YAAY,EAAE,0DAA0D;AACxE,IAAA,0BAA0B,EACxB,kEAAkE;AACpE,IAAA,YAAY,EACV,kEAAkE;AACpE,IAAA,mBAAmB,EACjB,kEAAkE;AACpE,IAAA,IAAI,EAAE,qBAAqB;CAC5B;AAED;;AAEG;AACH,IAAI,mBAAmB,GAA2B,EAAE,GAAG,mBAAmB,EAAE;AAE5E;;;;;;;;;;;AAWG;AACU,MAAA,eAAe,GAAG,CAC7B,aAAqC,KAC7B;IACR,mBAAmB,GAAG,EAAE,GAAG,mBAAmB,EAAE,GAAG,aAAa,EAAE;AACpE;AAEA;;;;;AAKG;AACI,MAAM,iBAAiB,GAAG,MAAW;IAC1C,mBAAmB,GAAG,EAAE;AAC1B;AAEA;;;;;;;;AAQG;MACU,eAAe,GAAG,MAC7B;AAEF;;;;;;;;;;;;;;AAcG;AACU,MAAA,eAAe,GAAG,CAAC,KAAsB,KAAY;;IAChE,MAAM,cAAc,GAAG,oDAAoD;IAC3E,IAAI,OAAO,GAAG,cAAc;IAC5B,IAAI,QAAQ,GAAG,EAAE;IAEjB,MAAM,aAAa,GAAG,CAAA,KAAK,aAAL,KAAK,KAAA,MAAA,GAAA,MAAA,GAAL,KAAK,CAAE,IAAI;AAC/B,UAAE,KAAK,CAAC,IAAI,CAAC,CAAC,GAAY,KAAK,GAAG,YAAY,6BAA6B;UACzE,IAAI;AACR,IAAA,IAAI,aAAa,YAAY,6BAA6B,EAAE;QAC1D,QAAQ;AACN,YAAA,CAAA,EAAA,GAAA,MAAA,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,aAAa,C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ED
|
@@ -54,6 +54,9 @@ export const useERC20ApproveX = (
|
|
|
54
54
|
const { writeContractAsync: approveTokenAsync, isPending } =
|
|
55
55
|
useContractWriteX({
|
|
56
56
|
queriesToInvalidate: [allowanceKQ],
|
|
57
|
+
onSuccess: () => {
|
|
58
|
+
setJustApproved(true);
|
|
59
|
+
},
|
|
57
60
|
});
|
|
58
61
|
|
|
59
62
|
useEffect(() => {
|
|
@@ -80,19 +83,12 @@ export const useERC20ApproveX = (
|
|
|
80
83
|
throw new Error("amountToApprove is undefined!");
|
|
81
84
|
}
|
|
82
85
|
|
|
83
|
-
await approveTokenAsync(
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
},
|
|
90
|
-
{
|
|
91
|
-
onSuccess: () => {
|
|
92
|
-
setJustApproved(true);
|
|
93
|
-
},
|
|
94
|
-
}
|
|
95
|
-
);
|
|
86
|
+
await approveTokenAsync({
|
|
87
|
+
address: tokenAddress,
|
|
88
|
+
abi: erc20Abi,
|
|
89
|
+
functionName: "approve",
|
|
90
|
+
args: [spenderAddress, amountToApprove],
|
|
91
|
+
});
|
|
96
92
|
} catch (e: any) {
|
|
97
93
|
console.error("Error approving token:", e);
|
|
98
94
|
throw e;
|