wagmi-extended 0.8.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +224 -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/{useToken.d.ts → useFetchAssetAllowanceX.d.ts} +50 -37
- 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/{useFetchAssetAllowance.d.ts → useTokenX.d.ts} +62 -108
- package/dist/index.cjs.js +353 -141
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +8 -4
- package/dist/index.esm.js +341 -138
- package/dist/index.esm.js.map +1 -1
- 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/{hooks/useToken.ts → fetch-functions/fetchTokenX.ts} +42 -30
- package/src/hooks/useContractWriteX.ts +84 -0
- package/src/hooks/{useERC20Approve.ts → useERC20ApproveX.ts} +42 -38
- package/src/hooks/useFetchAssetAllowanceX.ts +60 -0
- package/src/hooks/{useHandleTransactionMutation.ts → useHandleTransactionMutationX.ts} +3 -3
- package/src/hooks/{useSendTransactionExtended.ts → useSendTransactionX.ts} +35 -13
- package/src/hooks/useTokenX.ts +65 -0
- package/src/index.ts +27 -4
- package/src/utils/{errorParser.ts → errorParserX.ts} +1 -1
- package/dist/hooks/useERC20Approve.d.ts +0 -28
- package/src/hooks/useContractWriteExtended.ts +0 -44
- package/src/hooks/useFetchAssetAllowance.ts +0 -94
package/dist/index.cjs.js
CHANGED
|
@@ -73,7 +73,7 @@ const getErrorMapping = () => currentErrorMapping;
|
|
|
73
73
|
* const message = getParsedError(someError);
|
|
74
74
|
* console.log(message); // Outputs a custom error message or a default error message.
|
|
75
75
|
*/
|
|
76
|
-
const
|
|
76
|
+
const getParsedErrorX = (error) => {
|
|
77
77
|
var _a, _b, _c, _d;
|
|
78
78
|
const defaultMessage = "An unknown error occurred. Please contact support.";
|
|
79
79
|
let message = defaultMessage;
|
|
@@ -110,7 +110,7 @@ function useInvalidateQueries() {
|
|
|
110
110
|
*
|
|
111
111
|
* @returns {Function} A shared `onSettled` callback for transaction mutations.
|
|
112
112
|
*/
|
|
113
|
-
function
|
|
113
|
+
function useHandleTransactionMutationX({ settings, }) {
|
|
114
114
|
const wagmiConfig = wagmi.useConfig();
|
|
115
115
|
const { invalidateMany } = useInvalidateQueries();
|
|
116
116
|
const [isPending, setIsPending] = react.useState(false);
|
|
@@ -149,7 +149,7 @@ function useHandleTransactionMutation({ settings, }) {
|
|
|
149
149
|
return txHash;
|
|
150
150
|
}
|
|
151
151
|
catch (error) {
|
|
152
|
-
const parsedError =
|
|
152
|
+
const parsedError = getParsedErrorX(error);
|
|
153
153
|
if (!(settings === null || settings === void 0 ? void 0 : settings.disableLogging)) {
|
|
154
154
|
// 1. log error
|
|
155
155
|
console.error(`ContractWriteExtended Operation failed with error(parsed): ${parsedError}`, { error }, { args });
|
|
@@ -178,7 +178,7 @@ function useHandleTransactionMutation({ settings, }) {
|
|
|
178
178
|
/**
|
|
179
179
|
* Custom hook for writing to a smart contract using Wagmi.
|
|
180
180
|
*
|
|
181
|
-
* 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.
|
|
182
182
|
*
|
|
183
183
|
* @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.
|
|
184
184
|
* @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.
|
|
@@ -191,9 +191,49 @@ function useHandleTransactionMutation({ settings, }) {
|
|
|
191
191
|
* - {boolean} isPending - Indicates whether the transaction is pending.
|
|
192
192
|
* - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.
|
|
193
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
|
+
* }
|
|
194
234
|
*/
|
|
195
|
-
function
|
|
196
|
-
const { isPending, errorMessage, onMutate, onSettled } =
|
|
235
|
+
function useContractWriteX(settings) {
|
|
236
|
+
const { isPending, errorMessage, onMutate, onSettled } = useHandleTransactionMutationX({
|
|
197
237
|
settings,
|
|
198
238
|
});
|
|
199
239
|
const { writeContractAsync, ...rest } = wagmi.useWriteContract({
|
|
@@ -215,7 +255,7 @@ function useContractWriteExtended(settings) {
|
|
|
215
255
|
*
|
|
216
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.
|
|
217
257
|
*
|
|
218
|
-
* @param {
|
|
258
|
+
* @param {WriteExtendedAsyncParams} [settings] - Optional settings for the write operation.
|
|
219
259
|
* @param {boolean} [settings.disableWaitingForReceipt] - Disables waiting for the transaction receipt.
|
|
220
260
|
* @param {boolean} [settings.disableLogging] - Disables logging the result of the transaction.
|
|
221
261
|
* @param {Function} [settings.onSuccess] - Callback function to be called on successful transaction.
|
|
@@ -226,9 +266,37 @@ function useContractWriteExtended(settings) {
|
|
|
226
266
|
* - {boolean} isPending - Indicates whether the transaction is pending.
|
|
227
267
|
* - {string|undefined} errorMessage - The error message, if an error occurred during the transaction.
|
|
228
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
|
+
* }
|
|
229
297
|
*/
|
|
230
|
-
function
|
|
231
|
-
const { isPending, errorMessage, onMutate, onSettled } =
|
|
298
|
+
function useSendTransactionX(settings) {
|
|
299
|
+
const { isPending, errorMessage, onMutate, onSettled } = useHandleTransactionMutationX({
|
|
232
300
|
settings,
|
|
233
301
|
});
|
|
234
302
|
const { sendTransactionAsync, ...rest } = wagmi.useSendTransaction({
|
|
@@ -254,12 +322,210 @@ const queryConfig = {
|
|
|
254
322
|
},
|
|
255
323
|
};
|
|
256
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
|
+
|
|
257
517
|
const EthTokenData = {
|
|
258
518
|
symbol: "ETH",
|
|
259
519
|
decimals: 18,
|
|
260
520
|
name: "Ethereum",
|
|
261
521
|
};
|
|
262
|
-
async function
|
|
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
|
+
}
|
|
263
529
|
if (token === viem.zeroAddress)
|
|
264
530
|
return EthTokenData.decimals;
|
|
265
531
|
const decimals = await queryClient.fetchQuery({
|
|
@@ -272,7 +538,13 @@ async function fetchDecimals(token, queryClient, wagmiConfig) {
|
|
|
272
538
|
});
|
|
273
539
|
return decimals;
|
|
274
540
|
}
|
|
275
|
-
async function
|
|
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
|
+
}
|
|
276
548
|
if (token === viem.zeroAddress)
|
|
277
549
|
return EthTokenData.symbol;
|
|
278
550
|
const symbol = await queryClient.fetchQuery({
|
|
@@ -285,9 +557,15 @@ async function fetchSymbol(token, queryClient, wagmiConfig) {
|
|
|
285
557
|
});
|
|
286
558
|
return symbol;
|
|
287
559
|
}
|
|
288
|
-
async function
|
|
560
|
+
async function fetchNameX(token, queryClient, wagmiConfig) {
|
|
289
561
|
if (token === viem.zeroAddress)
|
|
290
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
|
+
}
|
|
291
569
|
const name = await queryClient.fetchQuery({
|
|
292
570
|
...query.readContractQueryOptions(wagmiConfig, {
|
|
293
571
|
address: token,
|
|
@@ -309,13 +587,13 @@ async function fetchName(token, queryClient, wagmiConfig) {
|
|
|
309
587
|
* @returns A `Token` object containing the symbol, decimals.
|
|
310
588
|
* @throws Will throw an error if symbol or decimals cannot be fetched.
|
|
311
589
|
*/
|
|
312
|
-
async function
|
|
590
|
+
async function fetchTokenX(token, queryClient, wagmiConfig) {
|
|
313
591
|
const [symbol, decimals, name] = await Promise.all([
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
592
|
+
fetchSymbolX(token, queryClient, wagmiConfig),
|
|
593
|
+
fetchDecimalsX(token, queryClient, wagmiConfig),
|
|
594
|
+
fetchNameX(token, queryClient, wagmiConfig),
|
|
317
595
|
]);
|
|
318
|
-
if (!symbol || !decimals) {
|
|
596
|
+
if (!symbol || !decimals || !name) {
|
|
319
597
|
throw new Error("Failed to fetch token data");
|
|
320
598
|
}
|
|
321
599
|
return {
|
|
@@ -325,145 +603,79 @@ async function fetchToken(token, queryClient, wagmiConfig) {
|
|
|
325
603
|
};
|
|
326
604
|
}
|
|
327
605
|
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
throw new Error("Failed to fetch token data or allowance");
|
|
340
|
-
}
|
|
341
|
-
return {
|
|
342
|
-
bigIntValue: allowance,
|
|
343
|
-
decimals: tokenData.decimals,
|
|
344
|
-
symbol: tokenData.symbol,
|
|
345
|
-
};
|
|
346
|
-
};
|
|
347
|
-
const HookFetchAssetAllowanceQK = (asset, spender, userAddress, config, queryClient) => [
|
|
348
|
-
"hookFetchAllowance",
|
|
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",
|
|
349
617
|
asset,
|
|
350
|
-
spender,
|
|
351
|
-
userAddress,
|
|
352
|
-
config,
|
|
353
|
-
queryClient,
|
|
354
618
|
];
|
|
355
619
|
/**
|
|
356
|
-
* Custom hook for fetching
|
|
620
|
+
* Custom hook for fetching token metadata using extended Wagmi functionality.
|
|
357
621
|
*
|
|
358
|
-
*
|
|
359
|
-
*
|
|
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
|
+
* }
|
|
360
648
|
*/
|
|
361
|
-
const
|
|
362
|
-
const config = wagmi.useConfig();
|
|
649
|
+
const useTokenX = (asset) => {
|
|
363
650
|
const queryClient = reactQuery.useQueryClient();
|
|
364
|
-
const
|
|
651
|
+
const config = wagmi.useConfig();
|
|
365
652
|
const { data, ...rest } = reactQuery.useQuery({
|
|
366
|
-
queryKey:
|
|
367
|
-
queryFn: () =>
|
|
368
|
-
enabled:
|
|
369
|
-
...queryConfig.sensitiveDataQueryConfig,
|
|
653
|
+
queryKey: HookFetchTokenQK(asset),
|
|
654
|
+
queryFn: () => fetchTokenX(asset, queryClient, config),
|
|
655
|
+
enabled: Boolean(asset),
|
|
370
656
|
});
|
|
371
657
|
return {
|
|
372
658
|
...rest,
|
|
373
659
|
data,
|
|
374
|
-
queryKey:
|
|
375
|
-
};
|
|
376
|
-
};
|
|
377
|
-
|
|
378
|
-
/**
|
|
379
|
-
* Helper function to determine human readable state of approve.
|
|
380
|
-
*
|
|
381
|
-
* @param {boolean} isApproved - Indicates if the approval is already done.
|
|
382
|
-
* @param {boolean} justApproved - Indicates if the user has just approved.
|
|
383
|
-
* @return {string} - The appropriate button text.
|
|
384
|
-
*/
|
|
385
|
-
function getApproveState(isApproved, justApproved) {
|
|
386
|
-
if (isApproved) {
|
|
387
|
-
return justApproved ? "Approve Confirmed" : "Approved";
|
|
388
|
-
}
|
|
389
|
-
return "Approve";
|
|
390
|
-
}
|
|
391
|
-
/**
|
|
392
|
-
* Custom hook for approving ERC20 token transfers.
|
|
393
|
-
*
|
|
394
|
-
* This hook provides functionality for approving ERC20 token transfers, checking the current allowance, and handling the approval transaction using Wagmi.
|
|
395
|
-
*
|
|
396
|
-
* @param {Address} tokenAddress - The address of the ERC20 token contract.
|
|
397
|
-
* @param {Address} spenderAddress - The address of the spender to approve the transfer to.
|
|
398
|
-
* @param {bigint} [amount=BigInt(0)] - The amount of tokens to approve for transfer. Defaults to 0.
|
|
399
|
-
* @returns {Object} Object containing the following properties:
|
|
400
|
-
* - {boolean} isApproved - Indicates whether the spender is already approved to transfer the specified amount of tokens.
|
|
401
|
-
* - {boolean} isApproving - Indicates whether an approval transaction is currently pending.
|
|
402
|
-
* - {Function} approveAsync - Function to trigger the approval transaction.
|
|
403
|
-
*/
|
|
404
|
-
const useERC20Approve = (tokenAddress, spenderAddress, amount) => {
|
|
405
|
-
const [isApproved, setIsApproved] = react.useState(false);
|
|
406
|
-
const [justApproved, setJustApproved] = react.useState(false);
|
|
407
|
-
const { data: allowance, queryKey } = useFetchAssetAllowance({
|
|
408
|
-
asset: tokenAddress,
|
|
409
|
-
spender: spenderAddress,
|
|
410
|
-
});
|
|
411
|
-
const { writeContractAsync: approveTokenAsync, isPending } = useContractWriteExtended({
|
|
412
|
-
queriesToInvalidate: [queryKey],
|
|
413
|
-
});
|
|
414
|
-
react.useEffect(() => {
|
|
415
|
-
if (amount == null) {
|
|
416
|
-
setIsApproved(false);
|
|
417
|
-
}
|
|
418
|
-
else if (allowance && allowance.bigIntValue >= amount) {
|
|
419
|
-
setIsApproved(true);
|
|
420
|
-
}
|
|
421
|
-
else {
|
|
422
|
-
setIsApproved(false);
|
|
423
|
-
}
|
|
424
|
-
}, [allowance, amount]);
|
|
425
|
-
const approveAsync = async () => {
|
|
426
|
-
const amountToApprove = amount;
|
|
427
|
-
if (!spenderAddress) {
|
|
428
|
-
throw new Error("spenderAddress is undefined!");
|
|
429
|
-
}
|
|
430
|
-
if (!tokenAddress) {
|
|
431
|
-
throw new Error("tokenAddress is undefined!");
|
|
432
|
-
}
|
|
433
|
-
if (amountToApprove == null) {
|
|
434
|
-
throw new Error("amountToApprove is undefined!");
|
|
435
|
-
}
|
|
436
|
-
try {
|
|
437
|
-
await approveTokenAsync({
|
|
438
|
-
address: tokenAddress,
|
|
439
|
-
abi: viem.erc20Abi,
|
|
440
|
-
functionName: "approve",
|
|
441
|
-
args: [spenderAddress, amountToApprove],
|
|
442
|
-
}, {
|
|
443
|
-
onSuccess: () => {
|
|
444
|
-
setJustApproved(true);
|
|
445
|
-
},
|
|
446
|
-
});
|
|
447
|
-
}
|
|
448
|
-
catch (e) {
|
|
449
|
-
console.error("Error approving token:", e);
|
|
450
|
-
throw e;
|
|
451
|
-
}
|
|
452
|
-
};
|
|
453
|
-
return {
|
|
454
|
-
isApproved,
|
|
455
|
-
isApproving: isPending,
|
|
456
|
-
justApproved,
|
|
457
|
-
approveAsync,
|
|
660
|
+
queryKey: HookFetchTokenQK(asset),
|
|
458
661
|
};
|
|
459
662
|
};
|
|
460
663
|
|
|
461
|
-
exports.
|
|
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;
|
|
462
671
|
exports.getErrorMapping = getErrorMapping;
|
|
463
|
-
exports.
|
|
672
|
+
exports.getParsedErrorX = getParsedErrorX;
|
|
464
673
|
exports.resetErrorMapping = resetErrorMapping;
|
|
674
|
+
exports.setDefaults = setDefaults;
|
|
465
675
|
exports.setErrorMapping = setErrorMapping;
|
|
466
|
-
exports.
|
|
467
|
-
exports.
|
|
468
|
-
exports.
|
|
676
|
+
exports.useContractWriteX = useContractWriteX;
|
|
677
|
+
exports.useERC20ApproveX = useERC20ApproveX;
|
|
678
|
+
exports.useFetchAssetAllowanceX = useFetchAssetAllowanceX;
|
|
679
|
+
exports.useSendTransactionX = useSendTransactionX;
|
|
680
|
+
exports.useTokenX = useTokenX;
|
|
469
681
|
//# sourceMappingURL=index.cjs.js.map
|