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

feat: sync chains and token with url #398

Merged
merged 9 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
34 changes: 29 additions & 5 deletions src/features/transfer/TransferTokenForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from '@hyperlane-xyz/widgets';
import BigNumber from 'bignumber.js';
import { Form, Formik, useFormikContext } from 'formik';
import { useRouter } from 'next/router';
import { useMemo, useState } from 'react';
import { toast } from 'react-toastify';
import { ConnectAwareSubmitButton } from '../../components/buttons/ConnectAwareSubmitButton';
Expand All @@ -20,6 +21,7 @@ import { TextField } from '../../components/input/TextField';
import { config } from '../../consts/config';
import { Color } from '../../styles/Color';
import { logger } from '../../utils/logger';
import { useMultipleQueryParams, useSyncQueryParam } from '../../utils/queryParams';
import { ChainConnectionWarning } from '../chains/ChainConnectionWarning';
import { ChainSelectField } from '../chains/ChainSelectField';
import { ChainWalletWarning } from '../chains/ChainWalletWarning';
Expand All @@ -38,6 +40,12 @@ import { useRecipientBalanceWatcher } from './useBalanceWatcher';
import { useFeeQuotes } from './useFeeQuotes';
import { useTokenTransfer } from './useTokenTransfer';

enum WARP_QUERY_PARAMS {
ORIGIN = 'origin',
DESTINATION = 'destination',
TOKEN = 'token',
}

export function TransferTokenForm() {
const multiProvider = useMultiProvider();
const warpCore = useWarpCore();
Expand All @@ -57,6 +65,8 @@ export function TransferTokenForm() {
setIsReview(true);
};

if (!initialValues) return null;

return (
<Formik<TransferFormValues>
initialValues={initialValues}
Expand Down Expand Up @@ -126,6 +136,11 @@ function ChainSelectSection({ isReview }: { isReview: boolean }) {
return getNumRoutesWithSelectedChain(warpCore, values.destination, false);
}, [values.destination, warpCore]);

useSyncQueryParam({
[WARP_QUERY_PARAMS.ORIGIN]: values.origin || '',
[WARP_QUERY_PARAMS.DESTINATION]: values.destination || '',
});

return (
<div className="mt-2 flex items-center justify-between gap-4">
<ChainSelectField
Expand Down Expand Up @@ -447,19 +462,28 @@ function WarningBanners() {
);
}

function useFormInitialValues(): TransferFormValues {
function useFormInitialValues(): TransferFormValues | null {
const warpCore = useWarpCore();
const { isReady } = useRouter();
const [defaultOriginQuery, defaultDestinationQuery] = useMultipleQueryParams([
WARP_QUERY_PARAMS.ORIGIN,
WARP_QUERY_PARAMS.DESTINATION,
]);

return useMemo(() => {
const firstToken = warpCore.tokens[0];
const connectedToken = firstToken.connections?.[0];

if (!isReady) return null;
Xaroz marked this conversation as resolved.
Show resolved Hide resolved

return {
origin: firstToken.chainName,
destination: connectedToken?.token?.chainName || '',
tokenIndex: getIndexForToken(warpCore, firstToken),
origin: defaultOriginQuery || firstToken.chainName,
destination: defaultDestinationQuery || connectedToken?.token?.chainName || '',
tokenIndex: defaultOriginQuery ? undefined : getIndexForToken(warpCore, firstToken),
amount: '',
recipient: '',
};
}, [warpCore]);
}, [warpCore, defaultOriginQuery, defaultDestinationQuery, isReady]);
}

const insufficientFundsErrMsg = /insufficient.[funds|lamports]/i;
Expand Down
51 changes: 51 additions & 0 deletions src/utils/queryParams.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { useRouter } from 'next/router';
import { ParsedUrlQuery } from 'querystring';
import { useEffect } from 'react';
import { logger } from './logger';

// To make Next's awkward query param typing more convenient
export function getQueryParamString(query: ParsedUrlQuery, key: string, defaultVal = '') {
if (!query) return defaultVal;
const val = query[key];
if (val && typeof val === 'string') return val;
else return defaultVal;
}

export function useMultipleQueryParams(keys: string[]) {
const router = useRouter();

return keys.map((key) => {
return getQueryParamString(router.query, key);
});
}

// Keep value in sync with query param in URL
export function useSyncQueryParam(params: Record<string, string>) {
const router = useRouter();
const { pathname, query } = router;
useEffect(() => {
let hasChanged = false;
const newQuery = new URLSearchParams(
Object.fromEntries(
Object.entries(query).filter((kv): kv is [string, string] => typeof kv[0] === 'string'),
),
);
Object.entries(params).forEach(([key, value]) => {
if (value && newQuery.get(key) !== value) {
newQuery.set(key, value);
hasChanged = true;
} else if (!value && newQuery.has(key)) {
newQuery.delete(key);
hasChanged = true;
}
});
if (hasChanged) {
const path = `${pathname}?${newQuery.toString()}`;
router
.replace(path, undefined, { shallow: true })
.catch((e) => logger.error('Error shallow updating URL', e));
}
// Must exclude router for next.js shallow routing, otherwise links break:
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [params]);
}
Loading