Skip to content

Commit

Permalink
Simplify local storage state management
Browse files Browse the repository at this point in the history
  • Loading branch information
MattPereira committed Aug 6, 2024
1 parent 14dde3f commit 70e352e
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 42 deletions.
52 changes: 36 additions & 16 deletions packages/nextjs/app/cow/_components/ManagePoolCreation.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { useEffect, useState } from "react";
import { StepsDisplay } from "./StepsDisplay";
import { Address } from "viem";
import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
import { Alert, TransactionButton } from "~~/components/common/";
// import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
import { TransactionButton } from "~~/components/common/";
import {
type ExistingPool,
useBindPool,
Expand All @@ -12,6 +12,7 @@ import {
useReadPool,
useSetSwapFee,
} from "~~/hooks/cow/";
import { useTargetNetwork } from "~~/hooks/scaffold-eth/useTargetNetwork";
import { useApproveToken, useReadToken } from "~~/hooks/token";

type TokenInput = {
Expand Down Expand Up @@ -44,24 +45,42 @@ export const ManagePoolCreation = ({
}: ManagePoolCreationProps) => {
const [currentStep, setCurrentStep] = useState(1);
const [userPoolAddress, setUserPoolAddress] = useState<Address>();
console.log("render");

const { targetNetwork } = useTargetNetwork();
const { data: pool, refetch: refetchPool } = useReadPool(userPoolAddress);
const { allowance: allowance1, refetchAllowance: refetchAllowance1 } = useReadToken(token1?.address, pool?.address);
const { allowance: allowance2, refetchAllowance: refetchAllowance2 } = useReadToken(token2?.address, pool?.address);
useNewPoolEvents(setUserPoolAddress); // grab / listen for user's pool creation events to set the target pool address
const refetchAllowances = () => {
refetchAllowance1();
refetchAllowance2();
};

const { mutate: createPool, isPending: isCreatePending, error: createPoolError } = useCreatePool();
const {
mutate: createPool,
isPending: isCreatePending,
// error: createPoolError,
} = useCreatePool();
const {
mutate: approve,
isPending: isApprovePending,
error: approveError,
} = useApproveToken(() => {
refetchAllowance1();
refetchAllowance2();
});
const { mutate: bind, isPending: isBindPending, error: bindError } = useBindPool();
const { mutate: setSwapFee, isPending: isSetSwapFeePending, error: setSwapFeeError } = useSetSwapFee();
const { mutate: finalizePool, isPending: isFinalizePending, error: finalizeError } = useFinalizePool();
// error: approveError,
} = useApproveToken(refetchAllowances);
const {
mutate: bind,
isPending: isBindPending,
// error: bindError,
} = useBindPool();
const {
mutate: setSwapFee,
isPending: isSetSwapFeePending,
// error: setSwapFeeError,
} = useSetSwapFee();
const {
mutate: finalizePool,
isPending: isFinalizePending,
// error: finalizeError,
} = useFinalizePool();

const handleCreatePool = () =>
createPool({ name, symbol }, { onSuccess: newPoolAddress => setUserPoolAddress(newPoolAddress) });
Expand Down Expand Up @@ -115,7 +134,7 @@ export const ManagePoolCreation = ({
// Binding the tokens sets the tokens permanently
currentStep > 3 ? setIsChangeTokensDisabled(true) : setIsChangeTokensDisabled(false);
// If user has no pools or their most recent pool is already finalized
if (userPoolAddress || pool?.isFinalized) {
if (!userPoolAddress || pool?.isFinalized) {
setCurrentStep(1);
}
// If user has created a pool, but not finalized and tokens not binded
Expand Down Expand Up @@ -148,9 +167,10 @@ export const ManagePoolCreation = ({
currentStep,
setIsChangeNameDisabled,
setIsChangeTokensDisabled,
targetNetwork,
]);

const txError = createPoolError || approveError || bindError || setSwapFeeError || finalizeError;
// const txError = createPoolError || approveError || bindError || setSwapFeeError || finalizeError;

return (
<>
Expand Down Expand Up @@ -227,14 +247,14 @@ export const ManagePoolCreation = ({
}
})()}
</div>
{txError && (
{/* {txError && (
<Alert type="error">
<div className="flex items-center gap-2">
<ExclamationTriangleIcon className="w-5 h-5" /> Error:{" "}
{(txError as { shortMessage?: string }).shortMessage || "An unknown error occurred"}
</div>
</Alert>
)}
)} */}
</>
);
};
34 changes: 9 additions & 25 deletions packages/nextjs/app/cow/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type CreatePoolFormData = {
isChangeTokensDisabled: boolean;
};

const INITIAL_FORM_DATA: CreatePoolFormData = {
const INITIAL_FORM_DATA = {
token1: { amount: "" },
token2: { amount: "" },
name: "",
Expand All @@ -36,34 +36,20 @@ const INITIAL_FORM_DATA: CreatePoolFormData = {

const CowAmm: NextPage = () => {
const { targetNetwork } = useTargetNetwork();
const localStorageKey = `CowAmmFormData-${targetNetwork.id}`;

const [formData, setFormData] = useLocalStorage<CreatePoolFormData>(
`createPoolFormData-${targetNetwork.id}`,
INITIAL_FORM_DATA,
);

const [previousNetworkId, setPreviousNetworkId] = useLocalStorage<string | null>(
"previousNetworkId",
targetNetwork.id.toString(),
);

const [formData, setFormData] = useLocalStorage<CreatePoolFormData>(localStorageKey, INITIAL_FORM_DATA);
const { token1, token2, name, symbol, hasAgreedToWarning, isChangeNameDisabled, isChangeTokensDisabled } = formData;

const { data: tokenList } = useFetchTokenList();
const { existingPool } = useCheckIfPoolExists(token1?.address, token2?.address);

const resetForm = () => {
localStorage.removeItem(`createPoolFormData-${targetNetwork.id}`);
setFormData(INITIAL_FORM_DATA);
};

const handleTokenChange = (tokenKey: "token1" | "token2", tokenData: Token) => {
setFormData(prev => ({
...prev,
[tokenKey]: {
...prev[tokenKey],
...tokenData,
amount: prev[tokenKey].amount,
},
}));
};
Expand Down Expand Up @@ -111,11 +97,16 @@ const CowAmm: NextPage = () => {
[setFormData],
);

const resetForm = () => {
localStorage.removeItem(localStorageKey);
setFormData(INITIAL_FORM_DATA);
};

// Autofill pool name and symbol based on selected tokens
useEffect(() => {
if (token1?.symbol && token2?.symbol) {
const newName = `Balancer CoW AMM 50 ${token1?.symbol} 50 ${token2?.symbol}`;
const newSymbol = `BCoW-50${token1?.symbol}-50${token2?.symbol}`;

setFormData(prev => ({
...prev,
name: newName,
Expand All @@ -124,13 +115,6 @@ const CowAmm: NextPage = () => {
}
}, [token1, token2, setFormData]);

useEffect(() => {
if (previousNetworkId !== targetNetwork.id.toString()) {
resetForm();
}
setPreviousNetworkId(targetNetwork.id.toString());
}, [targetNetwork.id, setPreviousNetworkId, previousNetworkId, resetForm]);

// Filter out tokens that have already been chosen
const selectableTokens = tokenList?.filter(
token => token.address !== token1.address && token.address !== token2.address,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const RainbowKitCustomConnectButton = () => {
{(() => {
if (!connected) {
return (
<button className="btn btn-primary btn-sm" onClick={openConnectModal} type="button">
<button className="btn btn-secondary rounded-xl ml-3" onClick={openConnectModal} type="button">
Connect Wallet
</button>
);
Expand Down

0 comments on commit 70e352e

Please sign in to comment.