wagmi-extended 0.5.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +220 -1
- package/dist/config/defaults.d.ts +40 -0
- package/dist/fetch-functions/fetchAllowanceX.d.ts +2 -0
- package/dist/fetch-functions/fetchTokenX.d.ts +24 -0
- package/dist/hooks/{useContractWriteExtended.d.ts → useContractWriteX.d.ts} +43 -3
- package/dist/hooks/useERC20ApproveX.d.ts +40 -0
- package/dist/hooks/useFetchAssetAllowanceX.d.ts +192 -0
- package/dist/hooks/{useHandleTransactionMutation.d.ts → useHandleTransactionMutationX.d.ts} +1 -1
- package/dist/hooks/{useSendTransactionExtended.d.ts → useSendTransactionX.d.ts} +31 -10
- package/dist/hooks/useTokenX.d.ts +204 -0
- package/dist/index.cjs.js +456 -27
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +8 -3
- package/dist/index.esm.js +446 -28
- package/dist/index.esm.js.map +1 -1
- package/dist/query-config/index.d.ts +8 -0
- package/dist/utils/{errorParser.d.ts → errorParserX.d.ts} +1 -1
- package/package.json +2 -2
- package/src/config/defaults.ts +60 -0
- package/src/fetch-functions/fetchAllowanceX.ts +22 -0
- package/src/fetch-functions/fetchTokenX.ts +134 -0
- package/src/hooks/useContractWriteX.ts +84 -0
- package/src/hooks/useERC20ApproveX.ts +108 -0
- package/src/hooks/useFetchAssetAllowanceX.ts +60 -0
- package/src/hooks/{useHandleTransactionMutation.ts → useHandleTransactionMutationX.ts} +4 -4
- package/src/hooks/{useSendTransactionExtended.ts → useSendTransactionX.ts} +35 -13
- package/src/hooks/useTokenX.ts +65 -0
- package/src/index.ts +27 -3
- package/src/query-config/index.ts +8 -0
- package/src/utils/{errorParser.ts → errorParserX.ts} +1 -1
- package/tsconfig.json +9 -1
- package/src/hooks/useContractWriteExtended.ts +0 -44
package/dist/index.cjs.js
CHANGED
|
@@ -2,23 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
var wagmi = require('wagmi');
|
|
4
4
|
var actions = require('wagmi/actions');
|
|
5
|
-
var reactQuery = require('@tanstack/react-query');
|
|
6
5
|
var react = require('react');
|
|
7
6
|
var viem = require('viem');
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
*
|
|
12
|
-
* @returns An object with the invalidateMany function.
|
|
13
|
-
*/
|
|
14
|
-
function useInvalidateQueries() {
|
|
15
|
-
const queryClient = reactQuery.useQueryClient();
|
|
16
|
-
const invalidateMany = async (queries) => {
|
|
17
|
-
const promises = queries.map((queryKey) => queryClient.invalidateQueries({ queryKey }));
|
|
18
|
-
await Promise.all(promises);
|
|
19
|
-
};
|
|
20
|
-
return { invalidateMany };
|
|
21
|
-
}
|
|
7
|
+
var reactQuery = require('@tanstack/react-query');
|
|
8
|
+
var actions$1 = require('viem/actions');
|
|
9
|
+
var query = require('wagmi/query');
|
|
22
10
|
|
|
23
11
|
/**
|
|
24
12
|
* Default error mapping that contains a set of error identifiers mapped to user-friendly error messages.
|
|
@@ -85,7 +73,7 @@ const getErrorMapping = () => currentErrorMapping;
|
|
|
85
73
|
* const message = getParsedError(someError);
|
|
86
74
|
* console.log(message); // Outputs a custom error message or a default error message.
|
|
87
75
|
*/
|
|
88
|
-
const
|
|
76
|
+
const getParsedErrorX = (error) => {
|
|
89
77
|
var _a, _b, _c, _d;
|
|
90
78
|
const defaultMessage = "An unknown error occurred. Please contact support.";
|
|
91
79
|
let message = defaultMessage;
|
|
@@ -103,12 +91,26 @@ const getParsedError = (error) => {
|
|
|
103
91
|
return message;
|
|
104
92
|
};
|
|
105
93
|
|
|
94
|
+
/**
|
|
95
|
+
* Hook to invalidate multiple queries in the React Query cache.
|
|
96
|
+
*
|
|
97
|
+
* @returns An object with the invalidateMany function.
|
|
98
|
+
*/
|
|
99
|
+
function useInvalidateQueries() {
|
|
100
|
+
const queryClient = reactQuery.useQueryClient();
|
|
101
|
+
const invalidateMany = async (queries) => {
|
|
102
|
+
const promises = queries.map((queryKey) => queryClient.invalidateQueries({ queryKey }));
|
|
103
|
+
await Promise.all(promises);
|
|
104
|
+
};
|
|
105
|
+
return { invalidateMany };
|
|
106
|
+
}
|
|
107
|
+
|
|
106
108
|
/**
|
|
107
109
|
* Custom hook to handle transaction mutations.
|
|
108
110
|
*
|
|
109
111
|
* @returns {Function} A shared `onSettled` callback for transaction mutations.
|
|
110
112
|
*/
|
|
111
|
-
function
|
|
113
|
+
function useHandleTransactionMutationX({ settings, }) {
|
|
112
114
|
const wagmiConfig = wagmi.useConfig();
|
|
113
115
|
const { invalidateMany } = useInvalidateQueries();
|
|
114
116
|
const [isPending, setIsPending] = react.useState(false);
|
|
@@ -147,7 +149,7 @@ function useHandleTransactionMutation({ settings, }) {
|
|
|
147
149
|
return txHash;
|
|
148
150
|
}
|
|
149
151
|
catch (error) {
|
|
150
|
-
const parsedError =
|
|
152
|
+
const parsedError = getParsedErrorX(error);
|
|
151
153
|
if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogging)) {
|
|
152
154
|
// 1. log error
|
|
153
155
|
console.error(`ContractWriteExtended Operation failed with error(parsed): ${parsedError}`, { error }, { args });
|
|
@@ -176,7 +178,7 @@ function useHandleTransactionMutation({ settings, }) {
|
|
|
176
178
|
/**
|
|
177
179
|
* Custom hook for writing to a smart contract using Wagmi.
|
|
178
180
|
*
|
|
179
|
-
* This hook provides functionality for
|
|
181
|
+
* 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.
|
|
180
182
|
*
|
|
181
183
|
* @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.
|
|
182
184
|
* @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.
|
|
@@ -189,9 +191,49 @@ function useHandleTransactionMutation({ settings, }) {
|
|
|
189
191
|
* - {boolean} isPending - Indicates whether the transaction is pending.
|
|
190
192
|
* - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.
|
|
191
193
|
* - {Function} writeContractAsync - Function to trigger the write operation.
|
|
194
|
+
*
|
|
195
|
+
/**
|
|
196
|
+
* Custom hook for writing a contract using Wagmi with extended functionality.
|
|
197
|
+
*
|
|
198
|
+
* This hook wraps Wagmi’s `useContractWriteX` with additional handling for
|
|
199
|
+
* waiting for a transaction receipt, logging control, and invalidation of specified queries.
|
|
200
|
+
*
|
|
201
|
+
* @param {WriteExtendedAsyncParams} [settings] - Optional settings for handling the transaction.
|
|
202
|
+
* @returns {Object} An object containing:
|
|
203
|
+
* - `isPending`: {boolean} indicating if the transaction is in progress.
|
|
204
|
+
* - `errorMessage`: {string|undefined} a potential error message.
|
|
205
|
+
* - `writeContractAsync`: {Function} a function to trigger the transaction.
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* // In your component:
|
|
209
|
+
* function MyTransactionComponent() {
|
|
210
|
+
* const { writeContractAsync, isPending, errorMessage } = useContractWriteX({
|
|
211
|
+
* onSuccess: (txHash) => console.log("Transaction successful:", txHash),
|
|
212
|
+
* onError: (error) => console.error("Transaction error:", error),
|
|
213
|
+
* queriesToInvalidate: [["userBalance"], ["userActivity"]],
|
|
214
|
+
* });
|
|
215
|
+
*
|
|
216
|
+
* const handleWrite = async () => {
|
|
217
|
+
* try {
|
|
218
|
+
* const txHash = await writeContractAsync({ transaction params here.. });
|
|
219
|
+
* console.log("Received txHash:", txHash);
|
|
220
|
+
* } catch (err) {
|
|
221
|
+
* console.error("Failed writing transaction:", err);`
|
|
222
|
+
* }
|
|
223
|
+
* };
|
|
224
|
+
*
|
|
225
|
+
* return (
|
|
226
|
+
* <div>
|
|
227
|
+
* <button onClick={handleWrite} disabled={isPending}>
|
|
228
|
+
* {isPending ? "Processing..." : "Write Transaction"}
|
|
229
|
+
* </button>
|
|
230
|
+
* {errorMessage && <p>Error: {errorMessage}</p>}
|
|
231
|
+
* </div>
|
|
232
|
+
* );
|
|
233
|
+
* }
|
|
192
234
|
*/
|
|
193
|
-
function
|
|
194
|
-
const { isPending, errorMessage, onMutate, onSettled } =
|
|
235
|
+
function useContractWriteX(settings) {
|
|
236
|
+
const { isPending, errorMessage, onMutate, onSettled } = useHandleTransactionMutationX({
|
|
195
237
|
settings,
|
|
196
238
|
});
|
|
197
239
|
const { writeContractAsync, ...rest } = wagmi.useWriteContract({
|
|
@@ -213,7 +255,7 @@ function useContractWriteExtended(settings) {
|
|
|
213
255
|
*
|
|
214
256
|
* 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.
|
|
215
257
|
*
|
|
216
|
-
* @param {
|
|
258
|
+
* @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.
|
|
217
259
|
* @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.
|
|
218
260
|
* @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.
|
|
219
261
|
* @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.
|
|
@@ -224,9 +266,37 @@ function useContractWriteExtended(settings) {
|
|
|
224
266
|
* - {boolean} isPending - Indicates whether the transaction is pending.
|
|
225
267
|
* - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.
|
|
226
268
|
* - {Function} sendTransactionAsync - Function to trigger the send transaction mutation.
|
|
269
|
+
|
|
270
|
+
* @example
|
|
271
|
+
* // In your component:
|
|
272
|
+
* function MyTransactionComponent() {
|
|
273
|
+
* const { sendTransactionAsync, isPending, errorMessage } = useSendTransactionX({
|
|
274
|
+
* onSuccess: (txHash) => console.log("Transaction successful:", txHash),
|
|
275
|
+
* onError: (error) => console.error("Transaction error:", error),
|
|
276
|
+
* queriesToInvalidate: [["userBalance"], ["userActivity"]],
|
|
277
|
+
* });
|
|
278
|
+
*
|
|
279
|
+
* const handleSend = async () => {
|
|
280
|
+
* try {
|
|
281
|
+
* const txHash = await sendTransactionAsync({ transaction params here.. });
|
|
282
|
+
* console.log("Received txHash:", txHash);
|
|
283
|
+
* } catch (err) {
|
|
284
|
+
* console.error("Failed sending transaction:", err);`
|
|
285
|
+
* }
|
|
286
|
+
* };
|
|
287
|
+
*
|
|
288
|
+
* return (
|
|
289
|
+
* <div>
|
|
290
|
+
* <button onClick={handleSend} disabled={isPending}>
|
|
291
|
+
* {isPending ? "Processing..." : "Send Transaction"}
|
|
292
|
+
* </button>
|
|
293
|
+
* {errorMessage && <p>Error: {errorMessage}</p>}
|
|
294
|
+
* </div>
|
|
295
|
+
* );
|
|
296
|
+
* }
|
|
227
297
|
*/
|
|
228
|
-
function
|
|
229
|
-
const { isPending, errorMessage, onMutate, onSettled } =
|
|
298
|
+
function useSendTransactionX(settings) {
|
|
299
|
+
const { isPending, errorMessage, onMutate, onSettled } = useHandleTransactionMutationX({
|
|
230
300
|
settings,
|
|
231
301
|
});
|
|
232
302
|
const { sendTransactionAsync, ...rest } = wagmi.useSendTransaction({
|
|
@@ -243,10 +313,369 @@ function useSendTransactionExtended(settings) {
|
|
|
243
313
|
};
|
|
244
314
|
}
|
|
245
315
|
|
|
316
|
+
const queryConfig = {
|
|
317
|
+
metadataQueryConfig: {
|
|
318
|
+
staleTime: Infinity,
|
|
319
|
+
},
|
|
320
|
+
sensitiveDataQueryConfig: {
|
|
321
|
+
staleTime: 60000,
|
|
322
|
+
},
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
const fetchAllowance = async (asset, spender, userAddress, config) => {
|
|
326
|
+
const allowance = await actions$1.readContract(config, {
|
|
327
|
+
address: asset,
|
|
328
|
+
abi: viem.erc20Abi,
|
|
329
|
+
functionName: "allowance",
|
|
330
|
+
args: [userAddress, spender],
|
|
331
|
+
});
|
|
332
|
+
if (allowance == null) {
|
|
333
|
+
throw new Error("Failed to fetch token data or allowance");
|
|
334
|
+
}
|
|
335
|
+
return allowance;
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
const HookFetchAssetAllowanceQK = (asset, spender, userAddress) => ["HookFetchAllowance", asset, spender, userAddress];
|
|
339
|
+
/**
|
|
340
|
+
* Custom hook for fetching asset allowance.
|
|
341
|
+
*
|
|
342
|
+
* @param {Address} asset - The address of the ERC20 token contract.
|
|
343
|
+
* @param {Address} spender - The address of the spender to check allowance for.
|
|
344
|
+
*
|
|
345
|
+
*
|
|
346
|
+
* @example
|
|
347
|
+
* // In your component:
|
|
348
|
+
* function AllowanceDisplay() {
|
|
349
|
+
* const { data: allowance, isLoading, error } = useFetchAssetAllowanceX({
|
|
350
|
+
* asset: "0xTokenAddressExample",
|
|
351
|
+
* spender: "0xSpenderAddressExample",
|
|
352
|
+
* });
|
|
353
|
+
*
|
|
354
|
+
* if (isLoading) return <div>Loading allowance...</div>;
|
|
355
|
+
* if (error) return <div>Error loading allowance</div>;
|
|
356
|
+
*
|
|
357
|
+
* return (
|
|
358
|
+
* <div>
|
|
359
|
+
* Current Allowance: {allowance}
|
|
360
|
+
* </div>
|
|
361
|
+
* );
|
|
362
|
+
* }
|
|
363
|
+
*/
|
|
364
|
+
const useFetchAssetAllowanceX = ({ asset, spender, }) => {
|
|
365
|
+
const config = wagmi.useConfig();
|
|
366
|
+
const { address: userAddress } = wagmi.useAccount();
|
|
367
|
+
const { data, ...rest } = reactQuery.useQuery({
|
|
368
|
+
queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),
|
|
369
|
+
queryFn: () => fetchAllowance(asset, spender, userAddress, config),
|
|
370
|
+
enabled: Boolean(asset) && Boolean(spender) && Boolean(userAddress),
|
|
371
|
+
...queryConfig.sensitiveDataQueryConfig,
|
|
372
|
+
});
|
|
373
|
+
return {
|
|
374
|
+
...rest,
|
|
375
|
+
data,
|
|
376
|
+
queryKey: HookFetchAssetAllowanceQK(asset, spender, userAddress),
|
|
377
|
+
};
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Custom hook for approving ERC20 token transfers.
|
|
382
|
+
*
|
|
383
|
+
* This hook provides functionality for approving ERC20 token transfers, checking the current allowance, and handling the approval transaction using Wagmi.
|
|
384
|
+
*
|
|
385
|
+
* @param {Address} tokenAddress - The address of the ERC20 token contract (the transfer from).
|
|
386
|
+
* @param {Address} spenderAddress - The address of the spender to approve the transfer to.
|
|
387
|
+
* @param {bigint} [amount=BigInt(0)] - The amount to approve for transfer. Defaults to undefined.
|
|
388
|
+
* @param {boolean} [approveMax=false] - Indicates whether to approve the maximum amount or a specific amount.
|
|
389
|
+
* @returns {Object} Object containing the following properties:
|
|
390
|
+
* - {boolean} isApproved - Indicates whether the spender is already approved to transfer the specified amount of tokens.
|
|
391
|
+
* - {boolean} isApproving - Indicates whether an approval transaction is currently pending.
|
|
392
|
+
* - {Function} approveAsync - Function to trigger the approval transaction.
|
|
393
|
+
*
|
|
394
|
+
* @example
|
|
395
|
+
* // In your component:
|
|
396
|
+
* function ApproveTokenButton(amountToApprove) {
|
|
397
|
+
* const tokenAddress = "0xTokenAddressExample";
|
|
398
|
+
* const spenderAddress = "0xSpenderAddressExample";
|
|
399
|
+
*
|
|
400
|
+
* const { isApproved, isApproving, justApproved, approveAsync } = useERC20ApproveX(
|
|
401
|
+
* tokenAddress,
|
|
402
|
+
* spenderAddress,
|
|
403
|
+
* parseUnits(amountToApprove.toString(), 18),
|
|
404
|
+
* );
|
|
405
|
+
*
|
|
406
|
+
* return (
|
|
407
|
+
* <button onClick={approveAsync} disabled={isApproving || isApproved}>
|
|
408
|
+
* {isApproving ? "Approving..." : isApproved ? "Approved" : "Approve Token"}
|
|
409
|
+
* </button>
|
|
410
|
+
* );
|
|
411
|
+
* }
|
|
412
|
+
*/
|
|
413
|
+
const useERC20ApproveX = (tokenAddress, spenderAddress, amount, approveMax) => {
|
|
414
|
+
const [isApproved, setIsApproved] = react.useState(false);
|
|
415
|
+
const [justApproved, setJustApproved] = react.useState(false);
|
|
416
|
+
const { data: allowance, queryKey: allowanceKQ } = useFetchAssetAllowanceX({
|
|
417
|
+
asset: tokenAddress,
|
|
418
|
+
spender: spenderAddress,
|
|
419
|
+
});
|
|
420
|
+
const { writeContractAsync: approveTokenAsync, isPending } = useContractWriteX({
|
|
421
|
+
queriesToInvalidate: [allowanceKQ],
|
|
422
|
+
});
|
|
423
|
+
react.useEffect(() => {
|
|
424
|
+
if (amount == null) {
|
|
425
|
+
setIsApproved(false);
|
|
426
|
+
}
|
|
427
|
+
else if (allowance && allowance >= amount) {
|
|
428
|
+
setIsApproved(true);
|
|
429
|
+
}
|
|
430
|
+
else {
|
|
431
|
+
setIsApproved(false);
|
|
432
|
+
}
|
|
433
|
+
}, [allowance, amount]);
|
|
434
|
+
const approveAsync = async () => {
|
|
435
|
+
const amountToApprove = approveMax ? viem.maxUint256 : amount;
|
|
436
|
+
try {
|
|
437
|
+
if (!spenderAddress) {
|
|
438
|
+
throw new Error("spenderAddress is undefined!");
|
|
439
|
+
}
|
|
440
|
+
if (!tokenAddress) {
|
|
441
|
+
throw new Error("tokenAddress is undefined!");
|
|
442
|
+
}
|
|
443
|
+
if (amountToApprove == null) {
|
|
444
|
+
throw new Error("amountToApprove is undefined!");
|
|
445
|
+
}
|
|
446
|
+
await approveTokenAsync({
|
|
447
|
+
address: tokenAddress,
|
|
448
|
+
abi: viem.erc20Abi,
|
|
449
|
+
functionName: "approve",
|
|
450
|
+
args: [spenderAddress, amountToApprove],
|
|
451
|
+
}, {
|
|
452
|
+
onSuccess: () => {
|
|
453
|
+
setJustApproved(true);
|
|
454
|
+
},
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
catch (e) {
|
|
458
|
+
console.error("Error approving token:", e);
|
|
459
|
+
throw e;
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
return {
|
|
463
|
+
isApproved,
|
|
464
|
+
isApproving: isPending,
|
|
465
|
+
justApproved,
|
|
466
|
+
approveAsync,
|
|
467
|
+
};
|
|
468
|
+
};
|
|
469
|
+
|
|
470
|
+
// You can adjust the type for wagmiConfig to match your needs.
|
|
471
|
+
let defaultQueryClient = null;
|
|
472
|
+
let defaultWagmiConfig = null;
|
|
473
|
+
/**
|
|
474
|
+
* Sets the default configuration values.
|
|
475
|
+
*
|
|
476
|
+
* @param queryClient - The default QueryClient instance.
|
|
477
|
+
* @param wagmiConfig - The default Wagmi configuration.
|
|
478
|
+
* @example
|
|
479
|
+
* //In your application initialization (e.g., index.tsx or App.tsx):
|
|
480
|
+
* import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
481
|
+
* import { wagmiConfig } from "/path/to/wagmi-config";
|
|
482
|
+
* import { setDefaults } from "wagmi-extended";
|
|
483
|
+
*
|
|
484
|
+
* const queryClient = new QueryClient();
|
|
485
|
+
*
|
|
486
|
+
* //Set defaults for the extended library functions.
|
|
487
|
+
* setDefaults(queryClient, wagmiConfig);
|
|
488
|
+
*
|
|
489
|
+
* //Now helper functions like fetchTokenX can use these defaults if no explicit parameters are provided.
|
|
490
|
+
*/
|
|
491
|
+
function setDefaults(queryClient, wagmiConfig) {
|
|
492
|
+
defaultQueryClient = queryClient;
|
|
493
|
+
defaultWagmiConfig = wagmiConfig;
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Retrieves the currently set default configurations.
|
|
497
|
+
*
|
|
498
|
+
* @throws Will throw an error if defaults are not initialized.
|
|
499
|
+
* @returns An object containing the default queryClient and wagmiConfig.
|
|
500
|
+
*
|
|
501
|
+
* @example
|
|
502
|
+
* // Usage in a helper function:
|
|
503
|
+
* import { getDefaults } from "wagmi-extended";
|
|
504
|
+
*
|
|
505
|
+
* function exampleFunction() {
|
|
506
|
+
* const { queryClient, wagmiConfig } = getDefaults();
|
|
507
|
+
* // Use queryClient and wagmiConfig as needed...
|
|
508
|
+
* }
|
|
509
|
+
*/
|
|
510
|
+
function getDefaults() {
|
|
511
|
+
if (!defaultQueryClient || !defaultWagmiConfig) {
|
|
512
|
+
throw new Error("Default configuration not set. Please call setDefaults() first.");
|
|
513
|
+
}
|
|
514
|
+
return { queryClient: defaultQueryClient, wagmiConfig: defaultWagmiConfig };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const EthTokenData = {
|
|
518
|
+
symbol: "ETH",
|
|
519
|
+
decimals: 18,
|
|
520
|
+
name: "Ethereum",
|
|
521
|
+
};
|
|
522
|
+
async function fetchDecimalsX(token, queryClient, wagmiConfig) {
|
|
523
|
+
if (!queryClient || !wagmiConfig) {
|
|
524
|
+
({ queryClient, wagmiConfig } = getDefaults());
|
|
525
|
+
}
|
|
526
|
+
if (!queryClient || !wagmiConfig) {
|
|
527
|
+
throw new Error("Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()");
|
|
528
|
+
}
|
|
529
|
+
if (token === viem.zeroAddress)
|
|
530
|
+
return EthTokenData.decimals;
|
|
531
|
+
const decimals = await queryClient.fetchQuery({
|
|
532
|
+
...query.readContractQueryOptions(wagmiConfig, {
|
|
533
|
+
address: token,
|
|
534
|
+
abi: viem.erc20Abi,
|
|
535
|
+
functionName: "decimals",
|
|
536
|
+
}),
|
|
537
|
+
...queryConfig.metadataQueryConfig,
|
|
538
|
+
});
|
|
539
|
+
return decimals;
|
|
540
|
+
}
|
|
541
|
+
async function fetchSymbolX(token, queryClient, wagmiConfig) {
|
|
542
|
+
if (!queryClient || !wagmiConfig) {
|
|
543
|
+
({ queryClient, wagmiConfig } = getDefaults());
|
|
544
|
+
}
|
|
545
|
+
if (!queryClient || !wagmiConfig) {
|
|
546
|
+
throw new Error("Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()");
|
|
547
|
+
}
|
|
548
|
+
if (token === viem.zeroAddress)
|
|
549
|
+
return EthTokenData.symbol;
|
|
550
|
+
const symbol = await queryClient.fetchQuery({
|
|
551
|
+
...query.readContractQueryOptions(wagmiConfig, {
|
|
552
|
+
address: token,
|
|
553
|
+
abi: viem.erc20Abi,
|
|
554
|
+
functionName: "symbol",
|
|
555
|
+
}),
|
|
556
|
+
...queryConfig.metadataQueryConfig,
|
|
557
|
+
});
|
|
558
|
+
return symbol;
|
|
559
|
+
}
|
|
560
|
+
async function fetchNameX(token, queryClient, wagmiConfig) {
|
|
561
|
+
if (token === viem.zeroAddress)
|
|
562
|
+
return EthTokenData.name;
|
|
563
|
+
if (!queryClient || !wagmiConfig) {
|
|
564
|
+
({ queryClient, wagmiConfig } = getDefaults());
|
|
565
|
+
}
|
|
566
|
+
if (!queryClient || !wagmiConfig) {
|
|
567
|
+
throw new Error("Could not find queryClient or wagmiConfig, either pass them as arguments or set them using setDefaults()");
|
|
568
|
+
}
|
|
569
|
+
const name = await queryClient.fetchQuery({
|
|
570
|
+
...query.readContractQueryOptions(wagmiConfig, {
|
|
571
|
+
address: token,
|
|
572
|
+
abi: viem.erc20Abi,
|
|
573
|
+
functionName: "name",
|
|
574
|
+
}),
|
|
575
|
+
...queryConfig.metadataQueryConfig,
|
|
576
|
+
});
|
|
577
|
+
return name;
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* Fetches the token metadata (symbol, decimals) for the given token address.
|
|
581
|
+
* Internally calls:
|
|
582
|
+
* - `fetchSymbol(token)` to retrieve the token symbol,
|
|
583
|
+
* - `fetchDecimals(token)` to retrieve the token decimals
|
|
584
|
+
* - `fetchName(token)` to retrieve the token name
|
|
585
|
+
*
|
|
586
|
+
* @param token - The address of the token.
|
|
587
|
+
* @returns A `Token` object containing the symbol, decimals.
|
|
588
|
+
* @throws Will throw an error if symbol or decimals cannot be fetched.
|
|
589
|
+
*/
|
|
590
|
+
async function fetchTokenX(token, queryClient, wagmiConfig) {
|
|
591
|
+
const [symbol, decimals, name] = await Promise.all([
|
|
592
|
+
fetchSymbolX(token, queryClient, wagmiConfig),
|
|
593
|
+
fetchDecimalsX(token, queryClient, wagmiConfig),
|
|
594
|
+
fetchNameX(token, queryClient, wagmiConfig),
|
|
595
|
+
]);
|
|
596
|
+
if (!symbol || !decimals || !name) {
|
|
597
|
+
throw new Error("Failed to fetch token data");
|
|
598
|
+
}
|
|
599
|
+
return {
|
|
600
|
+
symbol,
|
|
601
|
+
decimals,
|
|
602
|
+
name,
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Returns a query key for fetching token data.
|
|
608
|
+
*
|
|
609
|
+
* @param {Address | undefined} asset - The token address.
|
|
610
|
+
* @returns {Array} A unique query key for the token fetch.
|
|
611
|
+
*
|
|
612
|
+
* @example
|
|
613
|
+
* const queryKey = HookFetchTokenQK("0x123...");
|
|
614
|
+
*/
|
|
615
|
+
const HookFetchTokenQK = (asset) => [
|
|
616
|
+
"HookTokenWagmiExtended",
|
|
617
|
+
asset,
|
|
618
|
+
];
|
|
619
|
+
/**
|
|
620
|
+
* Custom hook for fetching token metadata using extended Wagmi functionality.
|
|
621
|
+
*
|
|
622
|
+
* This hook leverages React Query for data fetching and caching.
|
|
623
|
+
* It retrieves token metadata (such as symbol, decimals, name, etc.) for a given token address.
|
|
624
|
+
*
|
|
625
|
+
* @param {Address} [asset] - The token address.
|
|
626
|
+
* @returns {Object} An object with the following properties:
|
|
627
|
+
* - `data`: The token data (or undefined if not loaded).
|
|
628
|
+
* - `isLoading`: Boolean indicating if the data is loading.
|
|
629
|
+
* - `error`: Any error encountered during the fetch.
|
|
630
|
+
* - `queryKey`: The unique key used for the query.
|
|
631
|
+
*
|
|
632
|
+
* @example
|
|
633
|
+
* // In your component:
|
|
634
|
+
* function MyTokenComponent() {
|
|
635
|
+
* const { data, isLoading, error, queryKey } = useTokenX("0x123456...");
|
|
636
|
+
*
|
|
637
|
+
* if (isLoading) return <div>Loading token data...</div>;
|
|
638
|
+
* if (error) return <div>Error: {error.message}</div>;
|
|
639
|
+
*
|
|
640
|
+
* return (
|
|
641
|
+
* <div>
|
|
642
|
+
* <p>Token Symbol: {data.symbol}</p>
|
|
643
|
+
* <p>Decimals: {data.decimals}</p>
|
|
644
|
+
* <p>Name: {data.name}</p>
|
|
645
|
+
* </div>
|
|
646
|
+
* );
|
|
647
|
+
* }
|
|
648
|
+
*/
|
|
649
|
+
const useTokenX = (asset) => {
|
|
650
|
+
const queryClient = reactQuery.useQueryClient();
|
|
651
|
+
const config = wagmi.useConfig();
|
|
652
|
+
const { data, ...rest } = reactQuery.useQuery({
|
|
653
|
+
queryKey: HookFetchTokenQK(asset),
|
|
654
|
+
queryFn: () => fetchTokenX(asset, queryClient, config),
|
|
655
|
+
enabled: Boolean(asset),
|
|
656
|
+
});
|
|
657
|
+
return {
|
|
658
|
+
...rest,
|
|
659
|
+
data,
|
|
660
|
+
queryKey: HookFetchTokenQK(asset),
|
|
661
|
+
};
|
|
662
|
+
};
|
|
663
|
+
|
|
664
|
+
exports.EthTokenData = EthTokenData;
|
|
665
|
+
exports.HookFetchTokenQK = HookFetchTokenQK;
|
|
666
|
+
exports.fetchDecimalsX = fetchDecimalsX;
|
|
667
|
+
exports.fetchNameX = fetchNameX;
|
|
668
|
+
exports.fetchSymbolX = fetchSymbolX;
|
|
669
|
+
exports.fetchTokenX = fetchTokenX;
|
|
670
|
+
exports.getDefaults = getDefaults;
|
|
246
671
|
exports.getErrorMapping = getErrorMapping;
|
|
247
|
-
exports.
|
|
672
|
+
exports.getParsedErrorX = getParsedErrorX;
|
|
248
673
|
exports.resetErrorMapping = resetErrorMapping;
|
|
674
|
+
exports.setDefaults = setDefaults;
|
|
249
675
|
exports.setErrorMapping = setErrorMapping;
|
|
250
|
-
exports.
|
|
251
|
-
exports.
|
|
676
|
+
exports.useContractWriteX = useContractWriteX;
|
|
677
|
+
exports.useERC20ApproveX = useERC20ApproveX;
|
|
678
|
+
exports.useFetchAssetAllowanceX = useFetchAssetAllowanceX;
|
|
679
|
+
exports.useSendTransactionX = useSendTransactionX;
|
|
680
|
+
exports.useTokenX = useTokenX;
|
|
252
681
|
//# sourceMappingURL=index.cjs.js.map
|