Skip to content

Commit

Permalink
refactor: remove unnecessary hook call by refactoring code
Browse files Browse the repository at this point in the history
  • Loading branch information
kemuru committed May 22, 2024
1 parent 4b4ff85 commit c4b26cb
Show file tree
Hide file tree
Showing 9 changed files with 35 additions and 46 deletions.
14 changes: 8 additions & 6 deletions web/src/context/NewTransactionContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ interface INewTransactionContext {
setSellerAddress: (address: string) => void;
sendingQuantity: string;
setSendingQuantity: (quantity: string) => void;
sendingToken: string;
setSendingToken: (token: string) => void;
sendingToken: { address: string; symbol: string };
setSendingToken: (token: { address: string; symbol: string }) => void;
buyerAddress: string;
setBuyerAddress: (address: string) => void;
deadline: string;
Expand Down Expand Up @@ -61,7 +61,7 @@ const NewTransactionContext = createContext<INewTransactionContext>({
setSellerAddress: () => {},
sendingQuantity: "",
setSendingQuantity: () => {},
sendingToken: "",
sendingToken: { address: "", symbol: "" },
setSendingToken: () => {},
buyerAddress: "",
setBuyerAddress: () => {},
Expand Down Expand Up @@ -93,7 +93,9 @@ export const NewTransactionProvider: React.FC<{ children: React.ReactNode }> = (
const [receivingToken, setReceivingToken] = useState<string>(localStorage.getItem("receivingToken") || "");
const [sellerAddress, setSellerAddress] = useState<string>(localStorage.getItem("sellerAddress") || "");
const [sendingQuantity, setSendingQuantity] = useState<string>(localStorage.getItem("sendingQuantity") || "");
const [sendingToken, setSendingToken] = useState<string>(localStorage.getItem("sendingToken") || "");
const [sendingToken, setSendingToken] = useState<{ address: string; symbol: string }>(
JSON.parse(localStorage.getItem("sendingToken")) || { address: "", symbol: "" }
);
const [buyerAddress, setBuyerAddress] = useState<string>(localStorage.getItem("buyerAddress") || "");
const [isRecipientAddressResolved, setIsRecipientAddressResolved] = useState(false);
const [deadline, setDeadline] = useState<string>(localStorage.getItem("deadline") || "");
Expand All @@ -111,7 +113,7 @@ export const NewTransactionProvider: React.FC<{ children: React.ReactNode }> = (
setReceivingToken("");
setSellerAddress("");
setSendingQuantity("");
setSendingToken("");
setSendingToken({ address: "", symbol: "" });
setBuyerAddress("");
setDeadline("");
setNotificationEmail("");
Expand All @@ -128,7 +130,7 @@ export const NewTransactionProvider: React.FC<{ children: React.ReactNode }> = (
localStorage.setItem("receivingToken", receivingToken);
localStorage.setItem("buyerAddress", buyerAddress);
localStorage.setItem("sendingQuantity", sendingQuantity);
localStorage.setItem("sendingToken", sendingToken);
localStorage.setItem("sendingToken", JSON.stringify(sendingToken));
localStorage.setItem("sellerAddress", sellerAddress);
localStorage.setItem("deadline", deadline);
localStorage.setItem("notificationEmail", notificationEmail);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const DepositPaymentButton: React.FC = () => {
const ensResult = useEnsAddress({ name: sellerAddress, chainId: 1 });
const deadlineTimestamp = new Date(deadline).getTime();
const timeoutPayment = (deadlineTimestamp - currentTime) / 1000;
const isNativeTransaction = sendingToken === "native";
const isNativeTransaction = sendingToken?.address === "native";
const transactionValue = isNativeTransaction ? parseEther(sendingQuantity) : parseUnits(sendingQuantity, 18);

useEffect(() => {
Expand All @@ -64,7 +64,7 @@ const DepositPaymentButton: React.FC = () => {

const { data: allowance } = useContractRead({
enabled: !isNativeTransaction,
address: sendingToken,
address: sendingToken?.address,
abi: erc20ABI,
functionName: "allowance",
args: [address, escrowUniversalAddress?.[chain?.id]],
Expand Down Expand Up @@ -105,7 +105,7 @@ const DepositPaymentButton: React.FC = () => {
buyer: address,
seller: sellerAddress,
amount: sendingQuantity,
token: isNativeTransaction ? "native" : sendingToken,
token: isNativeTransaction ? "native" : sendingToken?.address,
timeoutPayment: timeoutPayment,
transactionUri: transactionUri,
},
Expand All @@ -132,7 +132,7 @@ const DepositPaymentButton: React.FC = () => {
ethAddressPattern.test(finalRecipientAddress),
args: [
transactionValue,
sendingToken,
sendingToken?.address,
BigInt(Math.floor(timeoutPayment)),
transactionUri,
finalRecipientAddress,
Expand All @@ -147,7 +147,7 @@ const DepositPaymentButton: React.FC = () => {

const { config: approveConfig } = usePrepareContractWrite({
enabled: !isNativeTransaction,
address: sendingToken,
address: sendingToken?.address,
abi: erc20ABI,
functionName: "approve",
args: [escrowUniversalAddress?.[chain?.id], transactionValue],
Expand Down
6 changes: 2 additions & 4 deletions web/src/pages/NewTransaction/Preview/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import PreviewCard from "components/PreviewCard";
import Header from "./Header";
import NavigationButtons from "../NavigationButtons";
import { useNativeTokenSymbol } from "hooks/useNativeTokenSymbol";
import { useERC20TokenSymbol } from "hooks/useERC20TokenSymbol";

const Container = styled.div`
display: flex;
Expand All @@ -26,9 +25,8 @@ const Preview: React.FC = () => {
deadline,
extraDescriptionUri,
} = useNewTransactionContext();
const isNativeTransaction = sendingToken === "native";
const isNativeTransaction = sendingToken.address === "native";
const nativeTokenSymbol = useNativeTokenSymbol();
const { erc20TokenSymbol } = useERC20TokenSymbol(sendingToken);

const { address } = useAccount();

Expand All @@ -37,7 +35,7 @@ const Preview: React.FC = () => {
<Header />
<PreviewCard
buyerAddress={address}
assetSymbol={isNativeTransaction ? nativeTokenSymbol : erc20TokenSymbol}
assetSymbol={isNativeTransaction ? nativeTokenSymbol : sendingToken.symbol}
overrideIsList={false}
isPreview={true}
deadline={new Date(deadline).getTime()}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const AddCustomTokenTab: React.FC<IAddCustomTokenTab> = ({ setTokens, setActiveT
}

setTokens((prevTokens) => {
const newTokens = [...prevTokens, { label: info.symbol, value: customToken, logo: info.logo }];
const newTokens = [...prevTokens, { symbol: info.symbol, address: customToken, logo: info.logo }];
localStorage.setItem("tokens", JSON.stringify(newTokens));
return newTokens;
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { Item, TokenLabel, TokenLogo } from "../TokenSelector";
interface ITokensTab {
searchQuery: string;
setSearchQuery: (value: string) => void;
filteredTokens: { label: string; value: string; logo: string }[];
handleSelectToken: (value: string) => void;
filteredTokens: { symbol: string; address: string; logo: string }[];
handleSelectToken: (token: { symbol: string; address: string; logo: string }) => void;
}

const TokensTab: React.FC<ITokensTab> = ({ searchQuery, setSearchQuery, filteredTokens, handleSelectToken }) => {
Expand All @@ -18,9 +18,9 @@ const TokensTab: React.FC<ITokensTab> = ({ searchQuery, setSearchQuery, filtered
<div>
<Field placeholder="Search..." value={searchQuery} onChange={handleSearch} />
{filteredTokens.map((token) => (
<Item key={token.value} onClick={() => handleSelectToken(token.value)}>
<TokenLogo src={token.logo} alt={`${token.label} logo`} />
<TokenLabel>{token.label}</TokenLabel>
<Item key={token.address} onClick={() => handleSelectToken(token)}>
<TokenLogo src={token.logo} alt={`${token?.symbol} logo`} />
<TokenLabel>{token.symbol}</TokenLabel>
</Item>
))}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,19 +102,19 @@ const TokenSelector: React.FC = () => {

useEffect(() => {
if (tokens.length > 0) {
const nativeToken = tokens.find((token) => token.value === "native");
setSendingToken(localStorage.getItem("selectedToken") || nativeToken.value);
const nativeToken = tokens.find((token) => token.address === "native");
setSendingToken(JSON.parse(localStorage.getItem("selectedToken")) || nativeToken);
}
}, [tokens]);

const handleSelectToken = (value: string) => {
setSendingToken(value);
localStorage.setItem("selectedToken", value);
const handleSelectToken = (token) => {
setSendingToken(token);
localStorage.setItem("selectedToken", JSON.stringify(token));
setIsOpen(false);
};

const filteredTokens =
tokens && tokens.filter((token) => token?.label?.toLowerCase().includes(searchQuery?.toLowerCase()));
tokens && tokens.filter((token) => token?.symbol?.toLowerCase().includes(searchQuery?.toLowerCase()));

return (
<TokenSelectorWrapper>
Expand All @@ -124,20 +124,9 @@ const TokenSelector: React.FC = () => {
{loading ? (
<StyledLogoSkeleton />
) : (
sendingToken && (
<TokenLogo
src={tokens.find((token) => token.value === sendingToken)?.logo}
alt={`${sendingToken} logo`}
/>
)
)}
{loading ? (
<Skeleton width={40} height={16} />
) : sendingToken ? (
tokens.find((token) => token.value === sendingToken)?.label
) : (
"Select a token"
sendingToken && <TokenLogo src={sendingToken.logo} alt={`${sendingToken.symbol} logo`} />
)}
{loading ? <Skeleton width={40} height={16} /> : sendingToken ? sendingToken.symbol : "Select a token"}
</DropdownContent>
<DropdownArrow />
</DropdownButton>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const TokenAndAmount: React.FC<ITokenAndAmount> = ({ quantity, setQuantity }) =>
const { sendingToken, setHasSufficientNativeBalance } = useNewTransactionContext();
const { data: balanceData } = useBalance({
address: address,
token: sendingToken === "native" ? undefined : sendingToken,
token: sendingToken?.address === "native" ? undefined : sendingToken?.address,
});
const [error, setError] = useState("");

Expand Down
4 changes: 2 additions & 2 deletions web/src/utils/fetchNativeToken.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export const fetchNativeToken = (chain) => {
return {
label: chain?.nativeCurrency?.symbol || "Native Token",
value: "native",
symbol: chain?.nativeCurrency?.symbol || "Native Token",
address: "native",
logo: "https://assets.coingecko.com/coins/images/279/thumb/ethereum.png",
};
};
6 changes: 3 additions & 3 deletions web/src/utils/initializeTokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ export const initializeTokens = async (address: string, setTokens, setLoading, c
const tokenList = balances.tokenBalances.map(async (token) => {
const tokenInfo = await fetchTokenInfo(token.contractAddress, alchemyInstance);
return {
label: tokenInfo.symbol,
value: token.contractAddress,
symbol: tokenInfo.symbol,
address: token.contractAddress,
logo: tokenInfo.logo,
};
});
const allTokens = [nativeToken, ...(await Promise.all(tokenList))];
const customTokens = JSON.parse(localStorage.getItem("tokens")) || [];
const combinedTokens = [
...allTokens,
...customTokens.filter((ct) => !allTokens.some((token) => token.value === ct.value)),
...customTokens.filter((customToken) => !allTokens.some((token) => token.address === customToken.address)),
];
setTokens(combinedTokens);
localStorage.setItem("tokens", JSON.stringify(combinedTokens));
Expand Down

0 comments on commit c4b26cb

Please sign in to comment.