Skip to content

Commit

Permalink
- handle unknown account error
Browse files Browse the repository at this point in the history
- add loading state to wallet store
  • Loading branch information
Jennievon committed Aug 21, 2024
1 parent cebf589 commit 8ea863c
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 51 deletions.
28 changes: 12 additions & 16 deletions tools/bridge-frontend/src/components/modules/bridge/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,14 @@ import { handleStorage } from "@/src/lib/utils/walletUtils";
import useWalletStore from "@/src/stores/wallet-store";

export default function Dashboard() {
const { provider, address, walletConnected, switchNetwork, isL1ToL2 } =
useWalletStore();
const {
provider,
address,
walletConnected,
switchNetwork,
isL1ToL2,
loading,
} = useWalletStore();
const { getNativeBalance, getTokenBalance, sendERC20, sendNative } =
useContract();
const intervalId = React.useRef<any>(null);
Expand Down Expand Up @@ -60,7 +66,6 @@ export default function Dashboard() {
const [fromChain, toChain, token, receiver, amount] = textValues;

const [fromTokenBalance, setFromTokenBalance] = React.useState<any>(0);
const [loading, setLoading] = React.useState(false);
const [open, setOpen] = React.useState(false);

const onSubmit = React.useCallback(
Expand All @@ -73,7 +78,6 @@ export default function Dashboard() {
return;
}
try {
setLoading(true);
const transactionData = { ...data, receiver: receiver || address };
toast({
title: "Bridge Transaction",
Expand Down Expand Up @@ -111,8 +115,6 @@ export default function Dashboard() {
}`,
variant: ToastType.DESTRUCTIVE,
});
} finally {
setLoading(false);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand All @@ -139,7 +141,6 @@ export default function Dashboard() {
async (event: any) => {
event.preventDefault();
try {
setLoading(true);
switchNetwork();
} catch (error) {
console.error("Network switch failed", error);
Expand All @@ -150,8 +151,6 @@ export default function Dashboard() {
}`,
variant: ToastType.DESTRUCTIVE,
});
} finally {
setLoading(false);
}
},
[switchNetwork]
Expand All @@ -167,7 +166,6 @@ export default function Dashboard() {
const fetchTokenBalance = async () => {
if (!token || !address) return;

setLoading(true);
try {
const selectedToken = tokens.find((t: IToken) => t.value === token);
if (!selectedToken) return;
Expand All @@ -179,8 +177,6 @@ export default function Dashboard() {
setFromTokenBalance(balance);
} catch (error) {
console.error("Failed to fetch balance:", error);
} finally {
setLoading(false);
}
};

Expand Down Expand Up @@ -232,25 +228,25 @@ export default function Dashboard() {
fromChains={fromChains}
tokens={tokens}
fromTokenBalance={fromTokenBalance}
loading={loading}
loading={loading || formState.isSubmitting}
setAmount={setAmount}
walletConnected={walletConnected}
/>
<SwitchNetworkButton
handleSwitchNetwork={handleSwitchNetwork}
loading={loading}
loading={loading || formState.isSubmitting}
/>
<TransferToSection
form={form}
toChains={toChains}
loading={loading}
loading={loading || formState.isSubmitting}
receiver={receiver}
address={address}
setOpen={setOpen}
/>
<SubmitButton
walletConnected={walletConnected}
loading={loading}
loading={loading || formState.isSubmitting}
fromTokenBalance={fromTokenBalance}
/>
</form>
Expand Down
12 changes: 5 additions & 7 deletions tools/bridge-frontend/src/hooks/useContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,11 @@ export const useContract = () => {
ManagementContractAddress,
} = memoizedConfig;

let prov = new ethers.providers.Web3Provider(provider);
const walletInstance = new ethers.Wallet(privateKey as string, prov);
let ethersProvider = new ethers.providers.Web3Provider(provider);
const walletInstance = new ethers.Wallet(
privateKey as string,
ethersProvider
);
const isL1 = isL1ToL2;
const bridgeAddress = isL1 ? L1Bridge : L2Bridge;
const messageBusAddress = isL1 ? MessageBusAddress : L2MessageBusAddress;
Expand Down Expand Up @@ -193,11 +196,6 @@ export const useContract = () => {
}

if (!signer || !provider) {
toast({
title: "Signer or provider not found",
description: "Confirm that your active account is connected",
variant: ToastType.DESTRUCTIVE,
});
return handleError(null, "Signer or provider not found");
}

Expand Down
7 changes: 6 additions & 1 deletion tools/bridge-frontend/src/lib/utils/contractUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ import { ethers } from "ethers";

const handleError = (error: any, customMessage: string) => {
console.error(customMessage, error);
throw new Error(customMessage);
if (error?.message?.includes("unknown account")) {
throw new Error(
"Ensure your wallet is unlocked and an account is connected"
);
}
throw new Error(error);
};

const constructMerkleTree = (leafEntries: any[], msgHash: string) => {
Expand Down
70 changes: 43 additions & 27 deletions tools/bridge-frontend/src/stores/wallet-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
initializeSigner,
setupEventListeners,
} from "@/src/lib/utils/walletEvents";
import { currentNetwork } from "../lib/utils";
import { currentNetwork } from "@/src/lib/utils";

const useWalletStore = create<IWalletState>((set, get) => ({
provider: null,
Expand All @@ -19,32 +19,43 @@ const useWalletStore = create<IWalletState>((set, get) => ({
walletConnected: false,
isL1ToL2: true,
isWrongNetwork: false,
loading: true,

initializeProvider: async () => {
const detectedProvider = await getEthereumProvider();
const newSigner = initializeSigner(detectedProvider);

//@ts-ignore
const chainId = await detectedProvider?.request({
method: requestMethods.getChainId,
params: [],
});

const isL1 = chainId === currentNetwork.l1;
const expectedChainId = isL1 ? currentNetwork.l1 : currentNetwork.l2;

set({
provider: detectedProvider,
signer: newSigner,
isL1ToL2: isL1,
isWrongNetwork: chainId !== expectedChainId,
});

const cleanup = setupEventListeners(detectedProvider, (address: string) => {
set({ address });
});

return cleanup;
try {
set({ loading: true });
const detectedProvider = await getEthereumProvider();
const newSigner = initializeSigner(detectedProvider);

//@ts-ignore
const chainId = await detectedProvider?.request({
method: requestMethods.getChainId,
params: [],
});

const isL1 = chainId === currentNetwork.l1;
const expectedChainId = isL1 ? currentNetwork.l1 : currentNetwork.l2;

set({
provider: detectedProvider,
signer: newSigner,
isL1ToL2: isL1,
isWrongNetwork: chainId !== expectedChainId,
});

const cleanup = setupEventListeners(
detectedProvider,
(address: string) => {
set({ address });
}
);

return cleanup;
} catch (error) {
console.error("Error initializing provider:", error);
} finally {
set({ loading: false });
}
},

connectWallet: async () => {
Expand Down Expand Up @@ -117,6 +128,7 @@ const useWalletStore = create<IWalletState>((set, get) => ({

switchNetwork: async () => {
const { provider, isL1ToL2 } = get();

if (!provider) {
toast({
title: "Error",
Expand All @@ -126,6 +138,8 @@ const useWalletStore = create<IWalletState>((set, get) => ({
return;
}

set({ loading: true });

const desiredNetwork = isL1ToL2 ? currentNetwork.l2 : currentNetwork.l1;

try {
Expand All @@ -146,8 +160,8 @@ const useWalletStore = create<IWalletState>((set, get) => ({
console.error("Error switching network:", error);
if (error.code === 4902) {
toast({
title: "Network Not Found",
description: "Network not found in wallet",
title: "Network not found",
description: error.message || "Network not found in wallet",
variant: ToastType.INFO,
});
} else {
Expand All @@ -157,6 +171,8 @@ const useWalletStore = create<IWalletState>((set, get) => ({
variant: ToastType.DESTRUCTIVE,
});
}
} finally {
set({ loading: false });
}
},

Expand Down
1 change: 1 addition & 0 deletions tools/bridge-frontend/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ export interface IWalletState {
walletConnected: boolean;
isL1ToL2: boolean;
isWrongNetwork: boolean;
loading: boolean;
initializeProvider: () => void;
connectWallet: () => void;
disconnectWallet: () => void;
Expand Down

0 comments on commit 8ea863c

Please sign in to comment.