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 2 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
7 changes: 7 additions & 0 deletions src/features/chains/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,10 @@ export function getNumRoutesWithSelectedChain(
data,
};
}

/**
* Check if given chainName has valid chain metadata
*/
export function isChainValid(chainName: string, multiProvider: MultiProtocolProvider) {
return !!chainName && !!multiProvider.tryGetChainMetadata(chainName);
}
24 changes: 19 additions & 5 deletions src/features/tokens/TokenSelectField.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { IToken } from '@hyperlane-xyz/sdk';
import { tryParseAmount } from '@hyperlane-xyz/utils';
import { ChevronIcon } from '@hyperlane-xyz/widgets';
import { useField, useFormikContext } from 'formik';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import { TokenIcon } from '../../components/icons/TokenIcon';
import { TransferFormValues } from '../transfer/types';
Expand All @@ -18,6 +20,7 @@ export function TokenSelectField({ name, disabled, setIsNft }: Props) {
const [field, , helpers] = useField<number | undefined>(name);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isAutomaticSelection, setIsAutomaticSelection] = useState(false);
const { query } = useRouter();

const warpCore = useWarpCore();

Expand All @@ -26,23 +29,34 @@ export function TokenSelectField({ name, disabled, setIsNft }: Props) {
const tokensWithRoute = warpCore.getTokensForRoute(origin, destination);
let newFieldValue: number | undefined;
let newIsAutomatic: boolean;

// Use token from persistance
Xaroz marked this conversation as resolved.
Show resolved Hide resolved
if (query.token && typeof query.token === 'string') {
Xaroz marked this conversation as resolved.
Show resolved Hide resolved
// Check if tokenIndex exists
const tokenIndex = tryParseAmount(query.token)?.toNumber();
if (tokenIndex !== undefined) {
const token = warpCore.tokens[tokenIndex];
Xaroz marked this conversation as resolved.
Show resolved Hide resolved
newFieldValue = token ? tokenIndex : undefined;
}
}
// No tokens available for this route
if (tokensWithRoute.length === 0) {
else if (tokensWithRoute.length === 0) {
newFieldValue = undefined;
newIsAutomatic = true;
}
// Exactly one found
else if (tokensWithRoute.length === 1) {
newFieldValue = getIndexForToken(warpCore, tokensWithRoute[0]);
newIsAutomatic = true;
// Multiple possibilities
} else {
newFieldValue = undefined;
newIsAutomatic = false;
}

if (tokensWithRoute.length <= 1) newIsAutomatic = true;
else newIsAutomatic = false;
Xaroz marked this conversation as resolved.
Show resolved Hide resolved

helpers.setValue(newFieldValue);
setIsAutomaticSelection(newIsAutomatic);
}, [warpCore, origin, destination, helpers]);
}, [warpCore, origin, destination, helpers, query.token]);

const onSelectToken = (newToken: IToken) => {
// Set the token address value in formik state
Expand Down
59 changes: 52 additions & 7 deletions src/features/transfer/TransferTokenForm.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { TokenAmount, WarpCore } from '@hyperlane-xyz/sdk';
import { ProtocolType, errorToString, isNullish, toWei } from '@hyperlane-xyz/utils';
import {
ProtocolType,
errorToString,
isNullish,
toWei,
tryParseAmount,
} from '@hyperlane-xyz/utils';
import {
AccountInfo,
ChevronIcon,
Expand All @@ -12,6 +18,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,11 +27,12 @@ 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';
import { useChainDisplayName, useMultiProvider } from '../chains/hooks';
import { getNumRoutesWithSelectedChain } from '../chains/utils';
import { getNumRoutesWithSelectedChain, isChainValid } from '../chains/utils';
import { useIsAccountSanctioned } from '../sanctions/hooks/useIsAccountSanctioned';
import { useStore } from '../store';
import { SelectOrInputTokenIds } from '../tokens/SelectOrInputTokenIds';
Expand All @@ -38,6 +46,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 +71,8 @@ export function TransferTokenForm() {
setIsReview(true);
};

if (!initialValues) return null;

return (
<Formik<TransferFormValues>
initialValues={initialValues}
Expand Down Expand Up @@ -126,6 +142,12 @@ 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 || '',
[WARP_QUERY_PARAMS.TOKEN]: values.tokenIndex !== undefined ? String(values.tokenIndex) : '',
});

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

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

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: isOriginQueryValid ? defaultOriginQuery : firstToken.chainName,
destination: isDestinationQueryValid
? defaultDestinationQuery
: connectedToken?.token?.chainName || '',
tokenIndex:
tryParseAmount(defaultTokenQuery)?.toNumber() || getIndexForToken(warpCore, firstToken),
amount: '',
recipient: '',
};
}, [warpCore]);
}, [
warpCore,
isReady,
defaultOriginQuery,
defaultDestinationQuery,
defaultTokenQuery,
isOriginQueryValid,
isDestinationQueryValid,
]);
}

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