Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor supported routes fetching #2875

Open
wants to merge 7 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions wormhole-connect/src/hooks/useAmountValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { useMemo } from 'react';
import { useSelector } from 'react-redux';
import { QuoteResult } from 'routes/operator';
import { RootState } from 'store';
import { RouteState } from 'store/transferInput';
import { isMinAmountError } from 'utils/sdkv2';

type HookReturn = {
Expand All @@ -13,7 +12,7 @@ type HookReturn = {

type Props = {
balance?: string | null;
routes: RouteState[];
routes: string[];
quotesMap: Record<string, QuoteResult | undefined>;
tokenSymbol: string;
isLoading: boolean;
Expand Down Expand Up @@ -51,7 +50,8 @@ export const useAmountValidation = (props: Props): HookReturn => {
);

const allRoutesFailed = useMemo(
() => props.routes.every((route) => !props.quotesMap[route.name]?.success),
() =>
props.routes.every((route) => props.quotesMap[route]?.success === false),
[props.routes, props.quotesMap],
);

Expand Down
47 changes: 24 additions & 23 deletions wormhole-connect/src/hooks/useFetchSupportedRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,45 @@
import { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useDebounce } from 'use-debounce';

import { RouteState, setRoutes } from 'store/transferInput';
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';

import type { RootState } from 'store';
import config from 'config';
import { getTokenDetails } from 'telemetry';

const useFetchSupportedRoutes = (): void => {
const dispatch = useDispatch();
type HookReturn = {
supportedRoutes: string[];
isFetching: boolean;
};

const useFetchSupportedRoutes = (): HookReturn => {
const [routes, setRoutes] = useState<string[]>([]);
const [isFetching, setIsFetching] = useState<boolean>(false);

const { token, destToken, fromChain, toChain, amount } = useSelector(
(state: RootState) => state.transferInput,
);

const { toNativeToken } = useSelector((state: RootState) => state.relay);

const [debouncedAmount] = useDebounce(amount, 500);

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this debounce is redundant with another one in AmountInput. causes unneeded delay.

useEffect(() => {
if (!fromChain || !toChain || !token || !destToken) {
dispatch(setRoutes([]));
setRoutes([]);
setIsFetching(false);
return;
}

let isActive = true;

const getSupportedRoutes = async () => {
const routes: RouteState[] = [];
setIsFetching(true);
const _routes: string[] = [];
await config.routes.forEach(async (name, route) => {
let supported = false;

try {
supported = await route.isRouteSupported(
token,
destToken,
debouncedAmount,
amount,
fromChain,
toChain,
);
Expand All @@ -53,11 +56,12 @@ const useFetchSupportedRoutes = (): void => {
console.error('Error when checking route is supported:', e, name);
}

routes.push({ name, supported });
_routes.push(name);
});

if (isActive) {
dispatch(setRoutes(routes));
setIsFetching(false);
setRoutes(_routes);
}
};

Expand All @@ -66,15 +70,12 @@ const useFetchSupportedRoutes = (): void => {
return () => {
isActive = false;
};
}, [
dispatch,
token,
destToken,
debouncedAmount,
fromChain,
toChain,
toNativeToken,
]);
}, [token, destToken, amount, fromChain, toChain, toNativeToken]);

return {
supportedRoutes: routes,
isFetching,
};
};

export default useFetchSupportedRoutes;
3 changes: 2 additions & 1 deletion wormhole-connect/src/hooks/useRoutesQuotesBulk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@
!params.sourceToken ||
!params.destChain ||
!params.destToken ||
!parseFloat(params.amount)
!parseFloat(params.amount) ||
routes.length === 0
) {
return;
}
Expand Down Expand Up @@ -100,8 +101,8 @@
clearTimeout(refreshTimeout);
}
};
}, [

Check warning on line 104 in wormhole-connect/src/hooks/useRoutesQuotesBulk.ts

View workflow job for this annotation

GitHub Actions / lint

React Hook useEffect has missing dependencies: 'params', 'refreshTimeout', and 'routes'. Either include them or remove the dependency array
routes.join(),

Check warning on line 105 in wormhole-connect/src/hooks/useRoutesQuotesBulk.ts

View workflow job for this annotation

GitHub Actions / lint

React Hook useEffect has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked
params.sourceChain,
params.sourceToken,
params.destChain,
Expand Down
57 changes: 25 additions & 32 deletions wormhole-connect/src/hooks/useSortedRoutesWithQuotes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,47 +4,34 @@ import type { RootState } from 'store';
import { routes } from '@wormhole-foundation/sdk';
import useRoutesQuotesBulk from 'hooks/useRoutesQuotesBulk';
import config from 'config';
import { RouteState } from 'store/transferInput';
import useFetchSupportedRoutes from './useFetchSupportedRoutes';

type Quote = routes.Quote<
routes.Options,
routes.ValidatedTransferParams<routes.Options>
>;

export type RouteWithQuote = {
route: RouteState;
route: string;
quote: Quote;
};

type HookReturn = {
allSupportedRoutes: RouteState[];
sortedRoutes: RouteState[];
allSupportedRoutes: string[];
sortedRoutes: string[];
sortedRoutesWithQuotes: RouteWithQuote[];
quotesMap: ReturnType<typeof useRoutesQuotesBulk>['quotesMap'];
isFetchingQuotes: boolean;
isFetching: boolean;
};

export const useSortedRoutesWithQuotes = (): HookReturn => {
const {
amount,
routeStates,
fromChain,
token,
toChain,
destToken,
preferredRouteName,
} = useSelector((state: RootState) => state.transferInput);
const { toNativeToken } = useSelector((state: RootState) => state.relay);
const { amount, fromChain, token, toChain, destToken, preferredRouteName } =
useSelector((state: RootState) => state.transferInput);

const supportedRoutes = useMemo(
() => (routeStates || []).filter((rs) => rs.supported),
[routeStates],
);
const { toNativeToken } = useSelector((state: RootState) => state.relay);

const supportedRoutesNames = useMemo(
() => supportedRoutes.map((r) => r.name),
[supportedRoutes],
);
const { supportedRoutes, isFetching: isFetchingSupportedRoutes } =
useFetchSupportedRoutes();

const useQuotesBulkParams = useMemo(
() => ({
Expand All @@ -58,15 +45,15 @@ export const useSortedRoutesWithQuotes = (): HookReturn => {
[parseFloat(amount), fromChain, token, toChain, destToken, toNativeToken],
);

const { quotesMap, isFetching } = useRoutesQuotesBulk(
supportedRoutesNames,
const { quotesMap, isFetching: isFetchingQuotes } = useRoutesQuotesBulk(
supportedRoutes,
useQuotesBulkParams,
);

const routesWithQuotes = useMemo(() => {
return supportedRoutes
.map((route) => {
const quote = quotesMap[route.name];
const quote = quotesMap[route];
if (quote?.success) {
return {
route,
Expand All @@ -83,15 +70,15 @@ export const useSortedRoutesWithQuotes = (): HookReturn => {
// Only routes with quotes are sorted.
const sortedRoutesWithQuotes = useMemo(() => {
return [...routesWithQuotes].sort((routeA, routeB) => {
const routeConfigA = config.routes.get(routeA.route.name);
const routeConfigB = config.routes.get(routeB.route.name);
const routeConfigA = config.routes.get(routeA.route);
const routeConfigB = config.routes.get(routeB.route);

// Prioritize preferred route to avoid flickering the UI
// when the preferred route gets autoselected
if (preferredRouteName) {
if (routeA.route.name === preferredRouteName) {
if (routeA.route === preferredRouteName) {
return -1;
} else if (routeB.route.name === preferredRouteName) {
} else if (routeB.route === preferredRouteName) {
return 1;
}
}
Expand Down Expand Up @@ -135,8 +122,14 @@ export const useSortedRoutesWithQuotes = (): HookReturn => {
sortedRoutes,
sortedRoutesWithQuotes,
quotesMap,
isFetchingQuotes: isFetching,
isFetching: isFetchingSupportedRoutes || isFetchingQuotes,
}),
[supportedRoutes, sortedRoutesWithQuotes, quotesMap, isFetching],
[
supportedRoutes,
sortedRoutesWithQuotes,
quotesMap,
isFetchingSupportedRoutes,
isFetchingQuotes,
],
);
};
23 changes: 1 addition & 22 deletions wormhole-connect/src/store/transferInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,9 @@ export type TransferValidations = {
receiveAmount: ValidationErr;
};

export type RouteState = {
name: string;
supported: boolean;
};

export interface TransferInputState {
showValidationState: boolean;
validations: TransferValidations;
routeStates: RouteState[] | undefined;
fromChain: Chain | undefined;
toChain: Chain | undefined;
token: string;
Expand Down Expand Up @@ -135,7 +129,6 @@ function getInitialState(): TransferInputState {
relayerFee: '',
receiveAmount: '',
},
routeStates: undefined,
fromChain: config.ui.defaultInputs?.fromChain || undefined,
toChain: config.ui.defaultInputs?.toChain || undefined,
token: config.ui.defaultInputs?.tokenKey || '',
Expand Down Expand Up @@ -235,12 +228,6 @@ export const transferInputSlice = createSlice({
) => {
state.route = payload;
},
setRoutes: (
state: TransferInputState,
{ payload }: PayloadAction<RouteState[]>,
) => {
state.routeStates = payload;
},
// user input
setToken: (
state: TransferInputState,
Expand Down Expand Up @@ -336,14 +323,7 @@ export const transferInputSlice = createSlice({
state.route = undefined;
return;
}
if (
state.routeStates &&
state.routeStates.some((rs) => rs.name === payload && rs.supported)
) {
state.route = payload;
} else {
state.route = undefined;
}
state.route = payload;
},
// clear inputs
clearTransfer: (state: TransferInputState) => {
Expand Down Expand Up @@ -444,7 +424,6 @@ export const selectChain = async (
export const {
setValidations,
setRoute,
setRoutes,
setToken,
setDestToken,
setFromChain,
Expand Down
12 changes: 7 additions & 5 deletions wormhole-connect/src/utils/transferValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,13 +262,15 @@ export const validate = async (
transferInput.token &&
transferInput.destToken &&
transferInput.amount &&
Number.parseFloat(transferInput.amount) >= 0 &&
transferInput.routeStates?.some((rs) => rs.supported) !== undefined
? true
: false;
Number.parseFloat(transferInput.amount) >= 0;

if (!isCanceled()) {
dispatch(setValidations({ validations, showValidationState }));
dispatch(
setValidations({
validations,
showValidationState: !!showValidationState,
}),
);
}
};

Expand Down
Loading
Loading