Skip to content

Commit

Permalink
fix: token and chain select defaultValue bug
Browse files Browse the repository at this point in the history
  • Loading branch information
Jennievon committed Aug 5, 2024
1 parent 71d9665 commit 60554ff
Show file tree
Hide file tree
Showing 7 changed files with 75 additions and 127 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,78 +9,51 @@ import {
} from "../../ui/select";
import useCustomHookForm from "@/src/hooks/useCustomHookForm";

export const ChainSelectFrom = ({
export const ChainSelect = ({
form,
chains,
name,
}: {
form: ReturnType<typeof useCustomHookForm>;
chains: Chain[];
name: string;
}) => {
console.log("🚀 ~ ChainSelect ~ ", name, form.getValues(name));
return (
<FormField
control={form.control}
name="fromChain"
render={({ field }) => (
<FormItem>
<Select defaultValue={field.value} onValueChange={field.onChange}>
<FormControl>
<SelectTrigger className="h-8 bg-muted">
<SelectValue placeholder={field.value || "Select Chain"} />
</SelectTrigger>
</FormControl>
<SelectContent>
{chains.map((chain: Chain) => (
<SelectItem
key={chain.value}
value={chain.value}
disabled={!chain.isEnabled}
>
{chain.name}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
);
};

export const ChainSelectTo = ({
form,
chains,
}: {
form: ReturnType<typeof useCustomHookForm>;
chains: Chain[];
}) => {
return (
<FormField
control={form.control}
name="toChain"
render={({ field }) => (
<FormItem>
<Select defaultValue={field.value} onValueChange={field.onChange}>
<FormControl>
<SelectTrigger className="h-8 bg-muted">
<SelectValue placeholder={field.value || "Select Chain"} />
</SelectTrigger>
</FormControl>
<SelectContent>
{chains.map((chain: Chain) => (
<SelectItem
key={chain.value}
value={chain.value}
disabled={!chain.isEnabled}
>
{chain.name}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
name={name}
render={({ field }) => {
console.log("🚀 ~", name, field.value.value);
return (
<FormItem>
<Select
defaultValue={field.value.value}
onValueChange={field.onChange}
>
<FormControl>
<SelectTrigger className="h-8 bg-muted">
<SelectValue
placeholder={field.value.value || "Select Chain"}
/>
</SelectTrigger>
</FormControl>
<SelectContent>
{chains.map((chain: Chain) => (
<SelectItem
key={chain.value}
value={chain.value}
disabled={!chain.isEnabled}
>
{chain.value}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
);
}}
/>
);
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from "react";
import React, { useEffect } from "react";
import {
CardHeader,
CardTitle,
Expand All @@ -10,7 +10,7 @@ import { Separator } from "../../ui/separator";
import { Form } from "@/src/components/ui/form";
import { toast } from "@/src/components/ui/use-toast";
import { DrawerDialog } from "../common/drawer-dialog";
import { L1TOKENS, L2TOKENS } from "@/src/lib/constants";
import { L1CHAINS, L1TOKENS, L2CHAINS, L2TOKENS } from "@/src/lib/constants";
import { useWatch } from "react-hook-form";
import useCustomHookForm from "@/src/hooks/useCustomHookForm";
import { useWalletStore } from "../../providers/wallet-provider";
Expand All @@ -21,39 +21,29 @@ import { SubmitButton } from "./submit-button";
import { SwitchNetworkButton } from "./switch-network-button";
import { TransferToSection } from "./transfer-to-section";
import { bridgeSchema } from "@/src/schemas/bridge";
import { isAddress } from "ethers/lib/utils";
import { handleStorage } from "@/src/lib/utils/walletUtils";

export default function Dashboard() {
const {
provider,
address,
walletConnected,
switchNetwork,
isL1ToL2,
fromChains,
toChains,
} = useWalletStore();
const { provider, address, walletConnected, switchNetwork, isL1ToL2 } =
useWalletStore();
const { getNativeBalance, getTokenBalance, sendERC20, sendNative } =
useContract();

const defaultValues = {
amount: "",
fromChain: fromChains[0].value,
toChain: toChains[0].value,
token: isL1ToL2 ? L1TOKENS[0].value : L2TOKENS[0].value,
fromChain: isL1ToL2 ? L1CHAINS[0] : L2CHAINS[0],
toChain: isL1ToL2 ? L2CHAINS[0] : L1CHAINS[0],
token: isL1ToL2 ? L1TOKENS[0] : L2TOKENS[0],
receiver: address,
amount: "",
};

const form = useCustomHookForm(bridgeSchema, { defaultValues });

const {
handleSubmit,
control,
setValue,
reset,
setError,
formState: { errors },
} = form;
const { handleSubmit, control, setValue, reset, setError, formState } = form;

const tokens = isL1ToL2 ? L1TOKENS : L2TOKENS;
const fromChains = isL1ToL2 ? L1CHAINS : L2CHAINS;
const toChains = isL1ToL2 ? L2CHAINS : L1CHAINS;

const textValues = useWatch({
control,
Expand All @@ -64,24 +54,22 @@ export default function Dashboard() {
const [loading, setLoading] = React.useState(false);
const [fromTokenBalance, setFromTokenBalance] = React.useState<any>(0);

const tokens = isL1ToL2 ? L1TOKENS : L2TOKENS;

const [open, setOpen] = React.useState(false);

useEffect(() => {
const storedReceiver = handleStorage.get("tenBridgeReceiver");
if (storedReceiver) {
setValue("receiver", storedReceiver);
}
}, []);

React.useEffect(() => {
const fetchTokenBalance = async (token: Token) => {
setLoading(true);
try {
const balance = token.isNative
? await getNativeBalance(
provider,
isAddress(receiver) ? receiver : address
)
: await getTokenBalance(
token.address,
isAddress(receiver) ? receiver : address,
provider
);
? await getNativeBalance(provider, address)
: await getTokenBalance(token.address, address, provider);
setFromTokenBalance(balance);
} catch (error) {
console.error(error);
Expand All @@ -91,12 +79,11 @@ export default function Dashboard() {
};

if (token) {
const selectedToken = tokens.find((t) => t.value === token);
if (selectedToken) {
fetchTokenBalance(selectedToken);
if (token) {
fetchTokenBalance(token);
}
}
}, [fromChain, token, amount, receiver, provider, tokens, isL1ToL2]);
}, [fromChain, token, amount, receiver, provider, isL1ToL2]);

const onSubmit = React.useCallback(
async (data: any) => {
Expand All @@ -108,7 +95,6 @@ export default function Dashboard() {
description: "Bridge transaction initiated",
variant: ToastType.INFO,
});
const token = tokens.find((t) => t.value === transactionData.token);
if (!token) throw new Error("Invalid token");

const sendTransaction = token.isNative ? sendNative : sendERC20;
Expand Down Expand Up @@ -139,7 +125,7 @@ export default function Dashboard() {
setLoading(false);
}
},
[address, tokens, fromChain]
[address, token]
);

const setAmount = React.useCallback(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,15 @@ export const TokenSelect = ({ form, tokens }: any) => {
name="token"
render={({ field }) => (
<FormItem>
<Select defaultValue={field.value} onValueChange={field.onChange}>
<Select
defaultValue={field.value.value}
onValueChange={field.onChange}
>
<FormControl>
<SelectTrigger className="h-8 dark:bg-[#292929]">
<SelectValue placeholder={field.value || "Select Token"} />
<SelectValue
placeholder={field.value.value || "Select Token"}
/>
</SelectTrigger>
</FormControl>
<SelectContent side="top">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Chain, Token } from "@/src/types";
import { Separator } from "../../ui/separator";
import { Skeleton } from "../../ui/skeleton";
import { AmountInput } from "./amount-input";
import { ChainSelectFrom } from "./chain-select";
import { ChainSelect } from "./chain-select";
import { PercentageButtons } from "./percentage-buttons";
import { TokenSelect } from "./token-select";
import useCustomHookForm from "@/src/hooks/useCustomHookForm";
Expand All @@ -28,7 +28,7 @@ export const TransferFromSection = ({
<div>
<div className="flex items-center justify-between mb-4">
<strong>Transfer from</strong>
<ChainSelectFrom form={form} chains={fromChains} />
<ChainSelect form={form} chains={fromChains} name="fromChain" />
</div>
<div className="bg-muted dark:bg-[#15171D] rounded-lg border">
<div className="flex items-center justify-between p-2">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { PlusIcon } from "lucide-react";
import { Button } from "../../ui/button";
import { Skeleton } from "../../ui/skeleton";
import TruncatedAddress from "../common/truncated-address";
import { ChainSelectTo } from "./chain-select";
import { ChainSelect } from "./chain-select";
import { Chain } from "@/src/types";
import { isAddress } from "ethers/lib/utils";
import useCustomHookForm from "@/src/hooks/useCustomHookForm";
Expand All @@ -26,7 +26,7 @@ export const TransferToSection = ({
<div>
<div className="flex items-center justify-between">
<strong>Transfer to</strong>
<ChainSelectTo form={form} chains={toChains} />
<ChainSelect form={form} chains={toChains} name="toChain" />
</div>
<div className="flex items-center justify-end">
<Button
Expand All @@ -40,7 +40,7 @@ export const TransferToSection = ({
</div>
<div className="bg-muted dark:bg-[#15171D]">
<div className="flex items-center justify-between p-2">
<strong className="text-lg">{form.getValues().token}</strong>
<strong className="text-lg">{form.getValues().token?.value}</strong>
<div className="flex flex-col items-end">
<p className="text-sm text-muted-foreground">You will receive:</p>
<strong className="text-lg float-right">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
WalletConnectionProviderProps,
WalletNetwork,
} from "@/src/types";
import { L1CHAINS, L2CHAINS } from "@/src/lib/constants";
import { requestMethods } from "@/src/routes";
import {
getEthereumProvider,
Expand All @@ -25,8 +24,6 @@ const WalletProvider = ({ children }: WalletConnectionProviderProps) => {
const [signer, setSigner] = useState<any>(null);
const [address, setAddress] = useState<string>("");
const [isL1ToL2, setIsL1ToL2] = useState<boolean>(true);
const [fromChains, setFromChains] = useState(L1CHAINS);
const [toChains, setToChains] = useState(L2CHAINS);

useEffect(() => {
const storedAddress = handleStorage.get("walletAddress");
Expand All @@ -36,8 +33,6 @@ const WalletProvider = ({ children }: WalletConnectionProviderProps) => {
setAddress(storedAddress);
setIsWalletConnected(true);
setIsL1ToL2(storedIsL1ToL2);
setFromChains(storedIsL1ToL2 ? L1CHAINS : L2CHAINS);
setToChains(storedIsL1ToL2 ? L2CHAINS : L1CHAINS);
}

const initializeProvider = async () => {
Expand All @@ -50,8 +45,6 @@ const WalletProvider = ({ children }: WalletConnectionProviderProps) => {

const isL1 = chainId === WalletNetwork.L1_SEPOLIA;
setIsL1ToL2(isL1);
setFromChains(isL1 ? L1CHAINS : L2CHAINS);
setToChains(isL1 ? L2CHAINS : L1CHAINS);
};

initializeProvider();
Expand All @@ -68,8 +61,6 @@ const WalletProvider = ({ children }: WalletConnectionProviderProps) => {

const isL1 = chainId === WalletNetwork.L1_SEPOLIA;
setIsL1ToL2(isL1);
setFromChains(isL1 ? L1CHAINS : L2CHAINS);
setToChains(isL1 ? L2CHAINS : L1CHAINS);

const accounts = await detectedProvider.request({
method: requestMethods.connectAccounts,
Expand Down Expand Up @@ -148,10 +139,7 @@ const WalletProvider = ({ children }: WalletConnectionProviderProps) => {
});
const isL1 = desiredNetwork === WalletNetwork.L1_SEPOLIA;
setIsL1ToL2(isL1);
setFromChains(isL1 ? L1CHAINS : L2CHAINS);
setToChains(isL1 ? L2CHAINS : L1CHAINS);
handleStorage.save("isL1ToL2", isL1.toString());
window.location.reload(); // Reload the page to apply changes
toast({
title: "Network Switched",
description: `Switched to ${
Expand Down Expand Up @@ -185,8 +173,6 @@ const WalletProvider = ({ children }: WalletConnectionProviderProps) => {
address,
walletConnected: isWalletConnected,
isL1ToL2,
fromChains,
toChains,
connectWallet,
disconnectWallet,
switchNetwork,
Expand Down
2 changes: 0 additions & 2 deletions contracts/src/bridge/frontend/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,6 @@ export interface WalletConnectionContextType {
address: string;
walletConnected: boolean;
isL1ToL2: boolean;
fromChains: Chain[];
toChains: Chain[];
connectWallet: () => void;
disconnectWallet: () => void;
switchNetwork: () => void;
Expand Down

0 comments on commit 60554ff

Please sign in to comment.