Skip to content

Commit

Permalink
feat: add timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
0xbulma committed Jul 16, 2023
1 parent 3d6fd35 commit e9cb9cb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 40 deletions.
24 changes: 9 additions & 15 deletions front/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,20 @@

import { useState } from "react";
import Header from "./components/Header";
import {
useAccount,
useNetwork,
useSwitchNetwork,
} from "wagmi";
import { useAccount, useNetwork, useSwitchNetwork } from "wagmi";
import { useConnectModal } from "@rainbow-me/rainbowkit";
import { getProofDataForAuth, getProofDataForClaim, getuserIdFromHex, signMessage } from "@/utils/misc";
import {
getProofDataForAuth,
getProofDataForClaim,
getuserIdFromHex,
signMessage,
} from "@/utils/misc";
import { mumbaiFork } from "@/utils/wagmi";
import {
SismoConnectButton, // the Sismo Connect React button displayed below
} from "@sismo-core/sismo-connect-react";
import { fundMyAccountOnLocalFork } from "@/utils/fundMyAccountOnLocalFork";
import {
AUTHS,
CLAIMS,
CONFIG,
AuthType,
ClaimType,
} from "@/app/sismo-connect-config";
import { AUTHS, CLAIMS, CONFIG, AuthType, ClaimType } from "@/app/sismo-connect-config";
import useContract from "@/utils/useContract";

/* ******************** Defines the chain to use *************************** */
Expand Down Expand Up @@ -116,7 +111,7 @@ export default function Home() {
</div>
{isConnected && !amountClaimed && error && (
<>
<p>{error}</p>
<p style={{ color: "#ff6347" }}>{error}</p>
{error.slice(0, 16) === "Please switch to" && (
<button onClick={() => switchNetwork?.(CHAIN.id)}>Switch chain</button>
)}
Expand Down Expand Up @@ -281,4 +276,3 @@ export default function Home() {
</>
);
}

46 changes: 21 additions & 25 deletions front/src/utils/useContract.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { useEffect, useState } from "react";
import { Chain, formatEther } from "viem";
import { Chain, TransactionReceipt, formatEther } from "viem";
import {
useAccount,
useContractWrite,
useNetwork,
usePrepareContractWrite,
usePublicClient,
useSwitchNetwork,
} from "wagmi";
import { waitForTransaction, readContract } from "@wagmi/core";
Expand Down Expand Up @@ -40,9 +39,6 @@ export default function useContract({
const [verifiedClaims, setVerifiedClaims] = useState<VerifiedClaim[]>();
const [verifiedAuths, setVerifiedAuths] = useState<VerifiedAuth[]>();
const [verifiedSignedMessage, setVerifiedSignedMessage] = useState<string>();
const [nonce, setNonce] = useState<number | null>(null);

const publicClient = usePublicClient();
const { chain: currentChain } = useNetwork();
const { isConnected, address } = useAccount({
onConnect: async ({ address }) => address && (await fundMyAccountOnLocalFork(address)),
Expand All @@ -54,8 +50,7 @@ export default function useContract({
functionName: "claimWithSismo",
args: [responseBytes],
chain,
nonce: nonce || undefined,
enabled: Boolean(responseBytes) && Boolean(typeof nonce === "number"),
enabled: Boolean(responseBytes),
};
const { config, error: wagmiSimulateError } = usePrepareContractWrite(contractCallInputs);
const { writeAsync } = useContractWrite(config);
Expand All @@ -65,21 +60,6 @@ export default function useContract({
setPageState("responseReceived");
}, [responseBytes]);

useEffect(() => {
if (!address) return;
if (currentChain?.id !== chain?.id) return;

const fetchNonce = async () => {
const nonce = await publicClient.getTransactionCount({
address: address || "0x00",
blockTag: "latest",
});
setNonce(nonce);
};

fetchNonce();
}, [address, chain, currentChain]);

/* ************* Handle simulateContract call & chain errors ************ */
useEffect(() => {
if (currentChain?.id !== chain.id) return setError(`Please switch to ${chain.name} network`);
Expand All @@ -101,7 +81,25 @@ export default function useContract({
setPageState("confirmingTransaction");
const tx = await writeAsync?.();
setPageState("verifying");
const txReceipt = tx && (await waitForTransaction({ hash: tx.hash }));
let txReceipt: TransactionReceipt | undefined;
if (chain.id === 5151111) {
const timeout = new Promise((_, reject) =>
setTimeout(
() =>
reject(
new Error(
"Local fork error: operation timed out after 15 seconds, if you are running a local fork on Anvil please make sure to reset your wallet nonce."
)
),
15000
)
);
const txReceiptPromise = tx && waitForTransaction({ hash: tx.hash });
const race = await Promise.race([txReceiptPromise, timeout]);
txReceipt = race as TransactionReceipt;
} else {
txReceipt = tx && (await waitForTransaction({ hash: tx.hash }));
}
if (txReceipt?.status === "success") {
setAmountClaimed(
formatEther((await readAirdropContract("balanceOf", [address])) as unknown as bigint)
Expand All @@ -113,8 +111,6 @@ export default function useContract({
}
} catch (e: any) {
setError(formatError(e));
} finally {
setNonce(null);
}
}

Expand Down

0 comments on commit e9cb9cb

Please sign in to comment.