Skip to content

Commit c16f47d

Browse files
committed
fix: handle wrong network and transaction lifecycle
1 parent a2f50be commit c16f47d

2 files changed

Lines changed: 16 additions & 15 deletions

File tree

src/hooks/useHandleWrongNetwork.tsx

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,22 @@
1-
import { useConnections, useSwitchChain } from "wagmi";
1+
import { useAccount, useSwitchChain } from "wagmi";
22
import { CHAIN } from "@/data/constants";
33

44
interface HandleWrongNetworkParams {
55
chainId?: number;
66
}
77

88
const useHandleWrongNetwork = () => {
9-
const activeConnection = useConnections();
9+
const { chainId: activeChainId, isConnected } = useAccount();
1010
const { switchChainAsync } = useSwitchChain();
11-
const isConnected = () => activeConnection[0] !== undefined;
1211

1312
const handleWrongNetwork = async (params?: HandleWrongNetworkParams) => {
1413
const chainId = params?.chainId ?? CHAIN.id;
1514

16-
const isWrongNetwork = () => activeConnection[0]?.chainId !== chainId;
17-
18-
if (!isConnected()) {
15+
if (!isConnected) {
1916
throw new Error("No active wallet connection found.");
2017
}
2118

22-
if (isWrongNetwork()) {
19+
if (activeChainId !== chainId) {
2320
await switchChainAsync({ chainId });
2421
}
2522
};

src/hooks/useTransactionLifecycle.tsx

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { sendEip712Transaction, sendTransaction } from "viem/zksync";
22
import { useConfig } from "wagmi";
3-
import { getWalletClient } from "wagmi/actions";
3+
import { getAccount, getWalletClient } from "wagmi/actions";
44
import { CHAIN } from "@/data/constants";
55
import { ERROR_NAMES, ERRORS } from "@/data/errors";
66
import getTransactionData from "@/helpers/getTransactionData";
@@ -27,6 +27,16 @@ const useTransactionLifecycle = () => {
2727
transactionType: string,
2828
onError: (error: ApolloClientError) => void
2929
) => {
30+
if (!getAccount(config).isConnected) {
31+
onError({
32+
message: ERRORS.SignWallet,
33+
name: transactionType
34+
});
35+
return null;
36+
}
37+
38+
await handleWrongNetwork();
39+
3040
const walletClient = await getWalletClient(config, {
3141
chainId: CHAIN.id
3242
}).catch(() => null);
@@ -39,13 +49,7 @@ const useTransactionLifecycle = () => {
3949
return null;
4050
}
4151

42-
await handleWrongNetwork();
43-
44-
return (
45-
(await getWalletClient(config, { chainId: CHAIN.id }).catch(
46-
() => walletClient
47-
)) ?? null
48-
);
52+
return walletClient;
4953
};
5054

5155
const handleSponsoredTransaction = async (

0 commit comments

Comments
 (0)