-
Notifications
You must be signed in to change notification settings - Fork 210
Expand file tree
/
Copy pathTokenSelectField.tsx
More file actions
221 lines (202 loc) · 7.92 KB
/
Copy pathTokenSelectField.tsx
File metadata and controls
221 lines (202 loc) · 7.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { Token } from '@hyperlane-xyz/sdk';
import { useField, useFormikContext } from 'formik';
import { useState } from 'react';
import { ChevronLargeIcon } from '../../components/icons/ChevronLargeIcon';
import { WARP_QUERY_PARAMS } from '../../consts/args';
import { updateQueryParams } from '../../utils/queryParams';
import { trackTokenSelectionEvent } from '../analytics/utils';
import { ChainEditModal } from '../chains/ChainEditModal';
import { useMultiProvider } from '../chains/hooks';
import { getChainDisplayName } from '../chains/utils';
import { TransferFormValues } from '../transfer/types';
import { shouldClearAddress } from '../transfer/utils';
import { getTokenByKeyFromMap, useCollateralGroups, useTokenByKeyMap, useTokens } from './hooks';
import { TokenChainIcon } from './TokenChainIcon';
import { TokenSelectionMode } from './types';
import { UnifiedTokenChainModal } from './UnifiedTokenChainModal';
import { checkTokenHasRoute, getTokenKey } from './utils';
type Props = {
name: string;
label?: string;
selectionMode: TokenSelectionMode;
disabled?: boolean;
setIsNft?: (value: boolean) => void;
showLabel?: boolean;
// TEMP(mc-preview-collateral-tooltip): Remove once temporary collateral hover UI is no longer needed.
hoverTooltipContent?: string;
};
export function TokenSelectField({
name,
label,
selectionMode,
disabled,
setIsNft,
showLabel = true,
hoverTooltipContent,
}: Props) {
const { values, setFieldValue } = useFormikContext<TransferFormValues>();
const [{ value: tokenKey }, , { setValue: setTokenKey }] = useField<string | undefined>(name);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingChain, setEditingChain] = useState<string | null>(null);
const collateralGroups = useCollateralGroups();
const tokens = useTokens();
const handleEditBack = () => {
setEditingChain(null);
setIsModalOpen(true);
};
const multiProvider = useMultiProvider();
const tokenMap = useTokenByKeyMap();
// Get the current token
const selectedToken = getTokenByKeyFromMap(tokenMap, tokenKey);
// Get the counterpart token (destination when selecting origin, origin when selecting destination)
const counterpartToken =
selectionMode === 'origin'
? getTokenByKeyFromMap(tokenMap, values.destinationTokenKey)
: getTokenByKeyFromMap(tokenMap, values.originTokenKey);
const handleSelectToken = (newToken: Token) => {
const newTokenKey = getTokenKey(newToken);
setTokenKey(newTokenKey);
// Track analytics - derive origin and destination from current tokens
const originToken = getTokenByKeyFromMap(tokenMap, values.originTokenKey);
const destToken = getTokenByKeyFromMap(tokenMap, values.destinationTokenKey);
const origin = selectionMode === 'origin' ? newToken.chainName : originToken?.chainName || '';
const destination =
selectionMode === 'destination' ? newToken.chainName : destToken?.chainName || '';
const destinationTokenSymbol =
selectionMode === 'destination' ? newToken.symbol : destToken?.symbol || '';
trackTokenSelectionEvent(
selectionMode,
newToken,
destinationTokenSymbol,
origin,
destination,
multiProvider,
);
// Update URL query params based on selection mode
if (selectionMode === 'origin') {
setFieldValue('amount', '');
// Auto-select destination if current one has no route from new origin
const currentDest = getTokenByKeyFromMap(tokenMap, values.destinationTokenKey);
const hasValidRoute =
currentDest && checkTokenHasRoute(newToken, currentDest, collateralGroups);
const queryParams: Record<string, string> = {
[WARP_QUERY_PARAMS.ORIGIN]: newToken.chainName,
[WARP_QUERY_PARAMS.ORIGIN_TOKEN]: newToken.symbol,
};
if (!hasValidRoute) {
const firstDest = tokens.find(
(t) =>
t.chainName !== newToken.chainName && checkTokenHasRoute(newToken, t, collateralGroups),
);
if (firstDest) {
setFieldValue('destinationTokenKey', getTokenKey(firstDest));
queryParams[WARP_QUERY_PARAMS.DESTINATION] = firstDest.chainName;
queryParams[WARP_QUERY_PARAMS.DESTINATION_TOKEN] = firstDest.symbol;
// Clear recipient if new destination protocol doesn't match
if (shouldClearAddress(multiProvider, values.recipient, firstDest.chainName)) {
setFieldValue('recipient', '');
}
}
}
updateQueryParams(queryParams);
} else {
// When destination changes, validate and clear custom recipient if protocol changed
const shouldClearRecipient = shouldClearAddress(
multiProvider,
values.recipient,
newToken.chainName,
);
if (shouldClearRecipient) setFieldValue('recipient', '');
updateQueryParams({
[WARP_QUERY_PARAMS.DESTINATION]: newToken.chainName,
[WARP_QUERY_PARAMS.DESTINATION_TOKEN]: newToken.symbol,
});
}
// Update NFT state if callback provided
if (setIsNft) {
setIsNft(newToken.isNft());
}
};
const openTokenSelectModal = () => {
if (!disabled) setIsModalOpen(true);
};
return (
<>
<div className="flex flex-col">
{showLabel && label && <span className="mb-1 pl-0.5 text-sm text-gray-600">{label}</span>}
<TokenButton
token={selectedToken}
disabled={disabled}
onClick={openTokenSelectModal}
multiProvider={multiProvider}
hoverTooltipContent={hoverTooltipContent}
/>
</div>
<UnifiedTokenChainModal
isOpen={isModalOpen}
close={() => setIsModalOpen(false)}
onSelect={handleSelectToken}
selectionMode={selectionMode}
counterpartToken={counterpartToken}
recipient={values.recipient}
onEditChain={setEditingChain}
/>
{editingChain && (
<ChainEditModal
isOpen={!!editingChain}
close={() => setEditingChain(null)}
onClickBack={handleEditBack}
chainName={editingChain}
/>
)}
</>
);
}
function TokenButton({
token,
disabled,
onClick,
multiProvider,
hoverTooltipContent,
}: {
token?: Token;
disabled?: boolean;
onClick: () => void;
multiProvider: ReturnType<typeof useMultiProvider>;
hoverTooltipContent?: string;
}) {
const chainDisplayName = token ? getChainDisplayName(multiProvider, token.chainName) : '';
return (
<button
type="button"
className={`${styles.base} ${disabled ? styles.disabled : styles.enabled}`}
onClick={onClick}
disabled={disabled}
>
{hoverTooltipContent && (
<span className="pointer-events-none absolute -top-2 left-1/2 z-20 w-max max-w-[260px] -translate-x-1/2 -translate-y-full rounded-md bg-gray-900 px-2 py-1 text-left font-secondary text-xs leading-tight text-white opacity-0 shadow-lg transition-opacity duration-150 group-hover:opacity-100">
{hoverTooltipContent}
</span>
)}
{token ? (
<div className="flex min-w-0 flex-1 items-center gap-2.5">
<TokenChainIcon token={token} size={36} />
<div className="flex min-w-0 flex-col items-start">
<span className="font-secondary text-lg font-normal text-gray-900">{token.symbol}</span>
<span className="text-sm text-gray-900">{chainDisplayName}</span>
</div>
</div>
) : (
<span className="text-sm text-gray-400">Select token</span>
)}
<div className="flex h-10 w-10 items-center justify-center rounded-full border border-gray-400 bg-white drop-shadow-button transition-colors duration-150 group-hover:bg-gray-50">
<ChevronLargeIcon width={14} height={18} />
</div>
</button>
);
}
const styles = {
base: 'relative w-full py-2 flex items-center justify-between transition-all rounded-xl px-1.5 border duration-150 border-gray-400/25 shadow-sm group',
enabled: 'hover:bg-gray-50 cursor-pointer',
disabled: 'cursor-not-allowed opacity-60',
};