Skip to content

Commit

Permalink
fix: resolve conflicts and set balance
Browse files Browse the repository at this point in the history
  • Loading branch information
cyphertrace committed Oct 20, 2022
2 parents 32f1ca6 + 6a6f769 commit 180ee06
Show file tree
Hide file tree
Showing 75 changed files with 890 additions and 794 deletions.
4 changes: 2 additions & 2 deletions apps/ui/src/components/AddForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ import {
useMultipleUserBalances,
usePool,
usePoolMath,
useSplTokenAccountsQuery,
useUserBalanceAmount,
useUserNativeBalances,
useUserSolanaTokenAccountsQuery,
useWallets,
} from "../hooks";
import {
Expand Down Expand Up @@ -206,7 +206,7 @@ export const AddForm = ({
poolTokens,
poolSpec.isLegacyPool ? undefined : poolSpec.ecosystem,
);
const { data: splTokenAccounts = null } = useSplTokenAccountsQuery();
const { data: splTokenAccounts = null } = useUserSolanaTokenAccountsQuery();
const startNewInteraction = useStartNewInteraction(() => {
setFormInputAmounts(poolTokens.map(() => "0"));
});
Expand Down
5 changes: 3 additions & 2 deletions apps/ui/src/components/RecentInteractions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { Fragment, useEffect } from "react";
import { useTranslation } from "react-i18next";

import { useEnvironment, useInteractionState } from "../core/store";
import { useSplTokenAccountsQuery, useWallets } from "../hooks";
import { useUserSolanaTokenAccountsQuery, useWallets } from "../hooks";
import { isEveryAddressConnected } from "../models";
import type { InteractionType } from "../models";

Expand All @@ -34,7 +34,8 @@ export const RecentInteractions = ({
loadInteractionStatesFromIdb(env).catch(console.error);
}, [env, loadInteractionStatesFromIdb]);

const { isSuccess: didLoadSplTokenAccounts } = useSplTokenAccountsQuery();
const { isSuccess: didLoadSplTokenAccounts } =
useUserSolanaTokenAccountsQuery();
const wallets = useWallets();
// Don’t display current interaction
const { recentInteractionId, interactionStates } = useInteractionState();
Expand Down
4 changes: 2 additions & 2 deletions apps/ui/src/components/RemoveForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ import {
usePoolMath,
useRemoveFeesEstimationQuery,
useRemoveFeesEstimationQueryV2,
useSplTokenAccountsQuery,
useUserLpBalances,
useUserNativeBalances,
useUserSolanaTokenAccountsQuery,
useWallets,
} from "../hooks";
import {
Expand Down Expand Up @@ -93,7 +93,7 @@ export const RemoveForm = ({
state: poolState,
} = usePool(poolSpec.id);
const poolMath = usePoolMath(poolSpec.id);
const { data: splTokenAccounts = null } = useSplTokenAccountsQuery();
const { data: splTokenAccounts = null } = useUserSolanaTokenAccountsQuery();
const startNewInteractionV1 = useStartNewInteraction(() => {
if (method === RemoveMethod.ExactOutput) {
setFormOutputAmounts(formOutputAmounts.map(() => "0"));
Expand Down
26 changes: 14 additions & 12 deletions apps/ui/src/components/SwapForm/SwapForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ import {
useErc20BalanceQuery,
useGetSwapFormErrors,
useSolanaClient,
useSolanaLiquidityQueries,
useSplTokenAccountsQuery,
useSplUserBalance,
useSolanaTokenAccountQueries,
useStartNewInteraction,
useSwapFeesEstimationQuery,
useUserNativeBalances,
useUserSolanaTokenAccountsQuery,
useUserSolanaTokenBalance,
} from "../../hooks";
import { mockOf, renderWithAppContext } from "../../testUtils";

Expand All @@ -37,9 +37,9 @@ jest.mock(

jest.mock("../../hooks/solana", () => ({
...jest.requireActual("../../hooks/solana"),
useSplTokenAccountsQuery: jest.fn(),
useSplUserBalance: jest.fn(),
useSolanaLiquidityQueries: jest.fn(),
useUserSolanaTokenAccountsQuery: jest.fn(),
useUserSolanaTokenBalance: jest.fn(),
useSolanaTokenAccountQueries: jest.fn(),
}));

jest.mock("../../hooks/solana/useSolanaClient", () => ({
Expand All @@ -66,13 +66,15 @@ jest.mock("../../hooks", () => ({

const useGetSwapFormErrorsMock = mockOf(useGetSwapFormErrors);
const useSolanaClientMock = mockOf(useSolanaClient);
const useSplTokenAccountsQueryMock = mockOf(useSplTokenAccountsQuery);
const useUserSolanaTokenAccountsQueryMock = mockOf(
useUserSolanaTokenAccountsQuery,
);
const useStartNewInteractionMock = mockOf(useStartNewInteraction);
const useSwapFeesEstimationQueryMock = mockOf(useSwapFeesEstimationQuery);
const useErc20BalanceQueryMock = mockOf(useErc20BalanceQuery);
const useUserNativeBalancesMock = mockOf(useUserNativeBalances);
const useSplUserBalanceMock = mockOf(useSplUserBalance);
const useSolanaLiquidityQueriesMock = mockOf(useSolanaLiquidityQueries);
const useUserSolanaTokenBalanceMock = mockOf(useUserSolanaTokenBalance);
const useSolanaTokenAccountQueriesMock = mockOf(useSolanaTokenAccountQueries);

const findFromTokenButton = () => screen.queryAllByRole("button")[0];
const findToTokenButton = () => screen.queryAllByRole("button")[3];
Expand All @@ -86,7 +88,7 @@ describe("SwapForm", () => {
},
} as Partial<CustomConnection> as unknown as CustomConnection,
});
useSplTokenAccountsQueryMock.mockReturnValue({
useUserSolanaTokenAccountsQueryMock.mockReturnValue({
data: [],
});

Expand All @@ -107,8 +109,8 @@ describe("SwapForm", () => {
useSwapFeesEstimationQueryMock.mockReturnValue(null);
useGetSwapFormErrorsMock.mockReturnValue(() => []);
useErc20BalanceQueryMock.mockReturnValue({ data: zero });
useSplUserBalanceMock.mockReturnValue(zero);
useSolanaLiquidityQueriesMock.mockReturnValue([
useUserSolanaTokenBalanceMock.mockReturnValue(zero);
useSolanaTokenAccountQueriesMock.mockReturnValue([
{ data: [] },
] as unknown as readonly UseQueryResult<readonly TokenAccount[], Error>[]);
});
Expand Down
4 changes: 2 additions & 2 deletions apps/ui/src/components/SwapForm/SwapForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ import {
useIsLargeSwap,
usePoolMaths,
usePools,
useSplTokenAccountsQuery,
useSwapFeesEstimationQuery,
useSwapOutputAmountEstimate,
useSwapTokensContext,
useUserBalanceAmount,
useUserNativeBalances,
useUserSolanaTokenAccountsQuery,
} from "../../hooks";
import {
useHasActiveInteraction,
Expand Down Expand Up @@ -59,7 +59,7 @@ export const SwapForm = ({ maxSlippageFraction }: Props): ReactElement => {
const { t } = useTranslation();
const config = useEnvironment(selectConfig, shallow);
const { notify } = useNotification();
const { data: splTokenAccounts = null } = useSplTokenAccountsQuery();
const { data: splTokenAccounts = null } = useUserSolanaTokenAccountsQuery();
const startNewInteraction = useStartNewInteraction(() => {
setFormInputAmount("");
});
Expand Down
67 changes: 38 additions & 29 deletions apps/ui/src/components/WormholeForm/WormholeForm.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ChainId, CHAIN_ID_SOLANA } from "@certusone/wormhole-sdk";
import { CHAIN_ID_TO_NAME } from "@certusone/wormhole-sdk";
import type { ChainId } from "@certusone/wormhole-sdk";
import { CHAIN_ID_SOLANA, CHAIN_ID_TO_NAME } from "@certusone/wormhole-sdk";
import {
EuiButton,
EuiCallOut,
Expand All @@ -21,7 +21,8 @@ import { useTranslation } from "react-i18next";
import type { EcosystemId } from "../../config";
import { wormholeTokens as rawWormholeTokens } from "../../config";
import { useNotification } from "../../core/store";
import { useWormholeErc20BalanceQuery, useWormholeTransfer } from "../../hooks";
import { useUserSolanaTokenBalance, useWormholeTransfer } from "../../hooks";
import { useWormholeErc20BalanceQuery } from "../../hooks/wormhole/useWormholeErc20BalanceQuery";
import { generateId } from "../../models";
import type {
TxResult,
Expand All @@ -37,7 +38,6 @@ import WormholeChainSelect from "./WormholeChainSelect";
import { WormholeTokenSelect } from "./WormholeTokenSelect";

import "./WormholeForm.scss";
import { useSplUserBalance } from "hooks/solana/useSplUserBalance";

const getDetailsByChainId = (
token: WormholeToken,
Expand Down Expand Up @@ -84,13 +84,13 @@ export const WormholeForm = (): ReactElement => {

const sourceDetails = getDetailsByChainId(currentToken, sourceChainId);
const targetDetails = getDetailsByChainId(currentToken, targetChainId);
const splBalance = useSplUserBalance(
const splBalance = useUserSolanaTokenBalance(
sourceChainId === CHAIN_ID_SOLANA ? sourceDetails : null,
{ enabled: sourceChainId === CHAIN_ID_SOLANA },
);
const { data: erc20Balance = null } =
useWormholeErc20BalanceQuery(sourceDetails);
const balance = splBalance ?? erc20Balance ?? null;
const balance = splBalance ?? erc20Balance;

const handleTxResult = (txResult: TxResult): void => {
setTxResults((previousResults) => [...previousResults, txResult]);
Expand Down Expand Up @@ -140,28 +140,36 @@ export const WormholeForm = (): ReactElement => {
handleSubmit();
};

const checkAmountErrors = useCallback(() => {
let errors: readonly string[] = [];
if (inputAmount.isNeg()) {
errors = [...errors, t("general.amount_of_tokens_invalid")];
} else if (inputAmount.lte(0)) {
errors = [...errors, t("general.amount_of_tokens_less_than_one")];
} else if (currentToken && new Decimal(inputAmount).gt(balance ?? 0)) {
errors = [...errors, t("general.amount_of_tokens_exceed_balance")];
} else {
errors = [];
}
setAmountErrors(errors);
}, [inputAmount, balance]);
const checkAmountErrors = useCallback(
(value: Decimal) => {
let errors: readonly string[] = [];
if (value.isNeg()) {
errors = [...errors, t("general.amount_of_tokens_invalid")];
} else if (value.lte(0)) {
errors = [...errors, t("general.amount_of_tokens_less_than_one")];
} else if (!balance || new Decimal(value).gt(balance)) {
errors = [...errors, t("general.amount_of_tokens_exceed_balance")];
} else {
errors = [];
}
setAmountErrors(errors);
},
[balance, t],
);

const handleTransferAmountChange = useCallback((value: string): void => {
if (value === "") {
setInputAmount(new Decimal(0));
} else {
setInputAmount(new Decimal(value));
}
checkAmountErrors();
}, []);
const handleTransferAmountChange = useCallback(
(value: string): void => {
let newValue = new Decimal(0);
if (value === "") {
setInputAmount(new Decimal(0));
} else {
setInputAmount(new Decimal(value));
newValue = new Decimal(value);
}
checkAmountErrors(newValue);
},
[checkAmountErrors],
);

return (
<EuiForm
Expand Down Expand Up @@ -197,7 +205,7 @@ export const WormholeForm = (): ReactElement => {
labelType="legend"
labelAppend={
<EuiText size="s">
{`${t("swap_form.user_balance")} ${balance ?? "-"}`}
{`${t("swap_form.user_balance")} ${balance?.toString() || "-"}`}
</EuiText>
}
isInvalid={amountErrors.length > 0}
Expand All @@ -209,6 +217,7 @@ export const WormholeForm = (): ReactElement => {
step={10 ** -currentToken.nativeDetails.decimals}
min={0}
onValueChange={handleTransferAmountChange}
onBlur={() => checkAmountErrors(inputAmount)}
isInvalid={amountErrors.length > 0}
/>
</EuiFormRow>
Expand Down Expand Up @@ -252,7 +261,7 @@ export const WormholeForm = (): ReactElement => {
fill
isLoading={isLoading}
isDisabled={
isLoading || inputAmount.isZero() || amountErrors?.length > 0
isLoading || inputAmount.isZero() || amountErrors.length > 0
}
>
{isLoading
Expand Down
3 changes: 0 additions & 3 deletions apps/ui/src/config/wormhole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@ import {
CHAIN_ID_OASIS,
CHAIN_ID_OPTIMISM,
CHAIN_ID_POLYGON,
CHAIN_ID_SOLANA,
CHAIN_ID_TO_NAME,
isEVMChain,
} from "@certusone/wormhole-sdk";
import type { ReadonlyRecord } from "@swim-io/utils";
import { WormholeChainId } from "@swim-io/wormhole";
Expand Down
Loading

0 comments on commit 180ee06

Please sign in to comment.