-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathTransferModule.tsx
More file actions
597 lines (541 loc) · 19.3 KB
/
TransferModule.tsx
File metadata and controls
597 lines (541 loc) · 19.3 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
import { Chain, Chains } from "@chain-registry/types";
import { ActionButton, Stack } from "@namada/components";
import { mapUndefined } from "@namada/utils";
import { IconTooltip } from "App/Common/IconTooltip";
import { InlineError } from "App/Common/InlineError";
import { routes } from "App/routes";
import { chainAssetsMapAtom } from "atoms/chain";
import BigNumber from "bignumber.js";
import clsx from "clsx";
import { useKeychainVersion } from "hooks/useKeychainVersion";
import { TransactionFeeProps } from "hooks/useTransactionFee";
import { wallets } from "integrations";
import { useAtomValue } from "jotai";
import { useCallback, useMemo, useState } from "react";
import { BsQuestionCircleFill } from "react-icons/bs";
import { Link, useLocation, useNavigate } from "react-router-dom";
import {
Address,
AddressWithAssetAndAmount,
AddressWithAssetAndAmountMap,
GasConfig,
LedgerAccountInfo,
WalletProvider,
} from "types";
import { filterAvailableAsssetsWithBalance } from "utils/assets";
import { checkKeychainCompatibleWithMasp } from "utils/compatibility";
import { getDisplayGasFee } from "utils/gas";
import { parseChainInfo } from "./common";
import { CurrentStatus } from "./CurrentStatus";
import { IbcChannels } from "./IbcChannels";
import { SelectAssetModal } from "./SelectAssetModal";
import { SelectChainModal } from "./SelectChainModal";
import { SelectWalletModal } from "./SelectWalletModal";
import { SuccessAnimation } from "./SuccessAnimation";
import { TransferArrow } from "./TransferArrow";
import { TransferDestination } from "./TransferDestination";
import { TransferSource } from "./TransferSource";
type TransferModuleConfig = {
wallet?: WalletProvider;
walletAddress?: string;
availableWallets?: WalletProvider[];
connected?: boolean;
availableChains?: Chains;
chain?: Chain;
isShieldedAddress?: boolean;
onChangeWallet?: (wallet: WalletProvider) => void;
onChangeChain?: (chain: Chain) => void;
onChangeShielded?: (isShielded: boolean) => void;
// Additional information if selected account is a ledger
ledgerAccountInfo?: LedgerAccountInfo;
};
export type TransferSourceProps = TransferModuleConfig & {
availableAssets?: AddressWithAssetAndAmountMap;
isLoadingAssets?: boolean;
selectedAssetAddress?: Address;
availableAmount?: BigNumber;
onChangeSelectedAsset?: (address: Address | undefined) => void;
amount?: BigNumber;
onChangeAmount?: (amount: BigNumber | undefined) => void;
};
export type IbcOptions = {
sourceChannel: string;
onChangeSourceChannel: (channel: string) => void;
destinationChannel?: string;
onChangeDestinationChannel?: (channel: string) => void;
};
export type TransferDestinationProps = TransferModuleConfig & {
enableCustomAddress?: boolean;
customAddress?: Address;
onChangeCustomAddress?: (address: Address) => void;
onChangeShielded?: (shielded: boolean) => void;
};
export type OnSubmitTransferParams = {
displayAmount: BigNumber;
destinationAddress: Address;
memo?: string;
};
export type TransferModuleProps = {
source: TransferSourceProps;
destination: TransferDestinationProps;
onSubmitTransfer?: (params: OnSubmitTransferParams) => void;
requiresIbcChannels?: boolean;
gasConfig?: GasConfig;
feeProps?: TransactionFeeProps;
changeFeeEnabled?: boolean;
submittingText?: string;
isSubmitting?: boolean;
errorMessage?: string;
currentStatus?: string;
currentStatusExplanation?: string;
completedAt?: Date;
buttonTextErrors?: Partial<Record<ValidationResult, string>>;
onComplete?: () => void;
} & (
| { isIbcTransfer?: false; ibcOptions?: undefined }
| { isIbcTransfer: true; ibcOptions: IbcOptions }
);
type ValidationResult =
| "NoAmount"
| "NoSourceWallet"
| "NoSourceChain"
| "NoSelectedAsset"
| "NoDestinationWallet"
| "NoDestinationChain"
| "NoTransactionFee"
| "NotEnoughBalance"
| "NotEnoughBalanceForFees"
| "KeychainNotCompatibleWithMasp"
| "NoLedgerConnected"
| "Ok";
export const TransferModule = ({
source,
destination,
gasConfig: gasConfigProp,
feeProps,
changeFeeEnabled,
submittingText,
isSubmitting,
isIbcTransfer,
ibcOptions,
requiresIbcChannels,
onSubmitTransfer,
errorMessage,
currentStatus,
currentStatusExplanation,
completedAt,
onComplete,
buttonTextErrors = {},
}: TransferModuleProps): JSX.Element => {
const navigate = useNavigate();
const location = useLocation();
const [walletSelectorModalOpen, setWalletSelectorModalOpen] = useState(false);
const [sourceChainModalOpen, setSourceChainModalOpen] = useState(false);
const [destinationChainModalOpen, setDestinationChainModalOpen] =
useState(false);
const [assetSelectorModalOpen, setAssetSelectorModalOpen] = useState(false);
const [customAddressActive, setCustomAddressActive] = useState(
destination.enableCustomAddress && !destination.availableWallets
);
const [memo, setMemo] = useState<undefined | string>();
const keychainVersion = useKeychainVersion();
const chainAssetsMap = useAtomValue(chainAssetsMapAtom);
const allUsersAssets = Object.values(chainAssetsMap) ?? [];
const gasConfig = gasConfigProp ?? feeProps?.gasConfig;
const displayGasFee = useMemo(() => {
return gasConfig ? getDisplayGasFee(gasConfig, chainAssetsMap) : undefined;
}, [gasConfig]);
const availableAssets: AddressWithAssetAndAmountMap = useMemo(() => {
return filterAvailableAsssetsWithBalance(source.availableAssets);
}, [source.availableAssets]);
const selectedAsset = mapUndefined(
(address) => source.availableAssets?.[address],
source.selectedAssetAddress
);
const availableAmountMinusFees = useMemo(() => {
const { selectedAssetAddress, availableAmount } = source;
if (
typeof selectedAssetAddress === "undefined" ||
typeof availableAmount === "undefined" ||
typeof availableAssets === "undefined"
) {
return undefined;
}
if (
!displayGasFee?.totalDisplayAmount ||
// Don't subtract if the gas token is different than the selected asset:
gasConfig?.gasToken !== selectedAssetAddress
) {
return availableAmount;
}
const amountMinusFees = availableAmount
.minus(displayGasFee.totalDisplayAmount)
.decimalPlaces(6);
return BigNumber.max(amountMinusFees, 0);
}, [source.selectedAssetAddress, source.availableAmount, displayGasFee]);
const validationResult = useMemo((): ValidationResult => {
if (!source.wallet) {
return "NoSourceWallet";
} else if (
(source.isShieldedAddress || destination.isShieldedAddress) &&
keychainVersion &&
!checkKeychainCompatibleWithMasp(keychainVersion)
) {
return "KeychainNotCompatibleWithMasp";
} else if (!source.chain) {
return "NoSourceChain";
} else if (!destination.chain) {
return "NoDestinationChain";
} else if (!source.selectedAssetAddress) {
return "NoSelectedAsset";
} else if (!hasEnoughBalanceForFees()) {
return "NotEnoughBalanceForFees";
} else if (!source.amount || source.amount.eq(0)) {
return "NoAmount";
} else if (
!availableAmountMinusFees ||
source.amount.gt(availableAmountMinusFees)
) {
return "NotEnoughBalance";
} else if (!destination.wallet && !destination.customAddress) {
return "NoDestinationWallet";
} else if (
(source.isShieldedAddress || destination.isShieldedAddress) &&
source.ledgerAccountInfo &&
!source.ledgerAccountInfo.deviceConnected
) {
return "NoLedgerConnected";
} else {
return "Ok";
}
}, [source, destination, gasConfig, availableAmountMinusFees]);
const onSubmit = (e: React.FormEvent): void => {
e.preventDefault();
const address = destination.customAddress || destination.walletAddress;
if (!source.amount) {
throw new Error("Amount is not valid");
}
if (!address) {
throw new Error("Address is not provided");
}
if (!source.selectedAssetAddress) {
throw new Error("Asset is not selected");
}
const params: OnSubmitTransferParams = {
displayAmount: source.amount,
destinationAddress: address.trim(),
memo,
};
onSubmitTransfer?.(params);
};
const onChangeWallet = (config: TransferModuleConfig) => (): void => {
// No callback available, do nothing
if (!config.onChangeWallet) return;
// User may choose between multiple options
if ((config.availableWallets || []).length > 1) {
setWalletSelectorModalOpen(true);
return;
}
// Fallback to default wallet prop
if (!config.availableWallets && config.wallet) {
config.onChangeWallet(config.wallet);
return;
}
// Do nothing if no alternatives are provided
if (!config.availableWallets) {
return;
}
// Do nothing if wallet address is set, and no other wallet is available
if (config.walletAddress && config.availableWallets.length <= 1) {
return;
}
setWalletSelectorModalOpen(true);
};
function hasEnoughBalanceForFees(): boolean {
// Skip if transaction fees will be handled by another wallet, like Keplr.
// (Ex: when users transfer from IBC to Namada)
if (source.wallet && source.wallet !== wallets.namada) {
return true;
}
if (!availableAssets || !gasConfig || !displayGasFee) {
return false;
}
// Find how much the user has in their account for the selected fee token
const feeTokenAddress = gasConfig.gasToken;
if (!availableAssets.hasOwnProperty(feeTokenAddress)) {
return false;
}
const assetDisplayAmount = availableAssets[feeTokenAddress].amount;
const feeDisplayAmount = displayGasFee?.totalDisplayAmount;
return assetDisplayAmount.gt(feeDisplayAmount);
}
const chainAcceptedAssets = useMemo(() => {
// Get available assets that are accepted by the chain
return Object.values(availableAssets).filter(({ asset }) => {
if (!source.chain) return true;
return allUsersAssets.some(
(chainAsset) =>
chainAsset?.symbol.toLowerCase() === asset?.symbol.toLowerCase()
);
});
}, [availableAssets, source.chain, allUsersAssets]);
const sortedAssets = useMemo(() => {
if (!chainAcceptedAssets.length) {
return [];
}
// Sort filtered assets by amount
return [...chainAcceptedAssets].sort(
(
asset1: AddressWithAssetAndAmount,
asset2: AddressWithAssetAndAmount
) => {
return asset1.amount.gt(asset2.amount) ? -1 : 1;
}
);
}, [chainAcceptedAssets]);
const getButtonTextError = (
id: ValidationResult,
defaultText: string
): string => {
if (buttonTextErrors.hasOwnProperty(id) && buttonTextErrors[id]) {
return buttonTextErrors[id];
}
return defaultText;
};
const getButtonText = (): string | JSX.Element => {
if (isSubmitting) {
return submittingText || "Submitting...";
}
const getText = getButtonTextError.bind(null, validationResult);
switch (validationResult) {
case "NoSourceWallet":
return getText("Select Wallet");
case "NoSourceChain":
case "NoDestinationChain":
return getText("Select Chain");
case "NoSelectedAsset":
return getText("Select Asset");
case "NoDestinationWallet":
return getText("Select Destination Wallet");
case "NoAmount":
return getText("Define an amount to transfer");
case "NoTransactionFee":
return getText("No transaction fee is set");
case "NotEnoughBalance":
return getText("Not enough balance");
case "NotEnoughBalanceForFees":
return getText("Not enough balance to pay for transaction fees");
case "KeychainNotCompatibleWithMasp":
return getText("Keychain is not compatible with MASP");
case "NoLedgerConnected":
return getText("Connect your ledger and open the Namada App");
}
if (!availableAmountMinusFees) {
return getText("Wallet amount not available");
}
return "Submit";
};
const buttonColor =
destination.isShieldedAddress || source.isShieldedAddress ?
"yellow"
: "white";
const renderLedgerTooltip = useCallback(
() => (
<IconTooltip
className="absolute w-4 h-4 top-0 right-0 mt-4 mr-5"
icon={<BsQuestionCircleFill className="w-4 h-4 text-yellow" />}
text={
<span>
If your device is connected and the app is open, please go to{" "}
<Link
onClick={(e) => {
e.preventDefault();
navigate(routes.settingsLedger, {
state: { backgroundLocation: location },
});
}}
to={routes.settingsLedger}
className="text-yellow"
>
Settings
</Link>{" "}
and pair your device with Namadillo.
</span>
}
/>
),
[]
);
return (
<>
<section className="max-w-[480px] mx-auto" role="widget">
<Stack
className={clsx({
"opacity-0 transition-all duration-300 pointer-events-none":
completedAt,
})}
as="form"
onSubmit={onSubmit}
>
<TransferSource
isConnected={Boolean(source.connected)}
wallet={source.wallet}
walletAddress={source.walletAddress}
asset={selectedAsset?.asset}
isLoadingAssets={source.isLoadingAssets}
chain={parseChainInfo(source.chain, source.isShieldedAddress)}
availableAmount={source.availableAmount}
availableAmountMinusFees={availableAmountMinusFees}
amount={source.amount}
openProviderSelector={onChangeWallet(source)}
openChainSelector={
source.onChangeChain && !isSubmitting ?
() => setSourceChainModalOpen(true)
: undefined
}
openAssetSelector={
source.onChangeSelectedAsset && !isSubmitting ?
() => setAssetSelectorModalOpen(true)
: undefined
}
onChangeAmount={source.onChangeAmount}
isShieldedAddress={source.isShieldedAddress}
onChangeShielded={source.onChangeShielded}
isSubmitting={isSubmitting}
/>
<i className="flex items-center justify-center w-11 mx-auto -my-8 relative z-10">
<TransferArrow
color={destination.isShieldedAddress ? "#FF0" : "#FFF"}
isAnimating={isSubmitting}
/>
</i>
<TransferDestination
wallet={destination.wallet}
walletAddress={destination.walletAddress}
chain={parseChainInfo(
destination.chain,
destination.isShieldedAddress
)}
isShieldedAddress={destination.isShieldedAddress}
onChangeShielded={destination.onChangeShielded}
address={destination.customAddress}
onToggleCustomAddress={
destination.enableCustomAddress && destination.availableWallets ?
setCustomAddressActive
: undefined
}
customAddressActive={customAddressActive}
openProviderSelector={() =>
destination.onChangeWallet && destination.wallet ?
destination.onChangeWallet(destination.wallet)
: undefined
}
openChainSelector={
destination.onChangeChain && !isSubmitting ?
() => setDestinationChainModalOpen(true)
: undefined
}
onChangeAddress={destination.onChangeCustomAddress}
memo={memo}
onChangeMemo={setMemo}
feeProps={feeProps}
changeFeeEnabled={changeFeeEnabled}
gasDisplayAmount={displayGasFee?.totalDisplayAmount}
gasAsset={displayGasFee?.asset}
destinationAsset={selectedAsset?.asset}
amount={source.amount}
isSubmitting={isSubmitting}
/>
{isIbcTransfer && requiresIbcChannels && (
<IbcChannels
isShielded={Boolean(
source.isShieldedAddress || destination.isShieldedAddress
)}
sourceChannel={ibcOptions.sourceChannel}
onChangeSource={ibcOptions.onChangeSourceChannel}
destinationChannel={ibcOptions.destinationChannel}
onChangeDestination={ibcOptions.onChangeDestinationChannel}
/>
)}
{!isSubmitting && <InlineError errorMessage={errorMessage} />}
{currentStatus && isSubmitting && (
<CurrentStatus
status={currentStatus}
explanation={currentStatusExplanation}
/>
)}
{!isSubmitting && onSubmitTransfer && (
<div className="relative">
<ActionButton
outlineColor={buttonColor}
backgroundColor={buttonColor}
backgroundHoverColor="transparent"
textColor="black"
textHoverColor={buttonColor}
disabled={validationResult !== "Ok" || isSubmitting}
>
{getButtonText()}
</ActionButton>
{validationResult === "NoLedgerConnected" &&
renderLedgerTooltip()}
</div>
)}
{validationResult === "KeychainNotCompatibleWithMasp" && (
<div className="text-center text-fail text-xs selection:bg-fail selection:text-white mb-12">
Please update your Namada Keychain in order to make shielded
transfers
</div>
)}
</Stack>
{completedAt && selectedAsset?.asset && source.amount && (
<SuccessAnimation
asset={selectedAsset.asset}
amount={source.amount}
onCompleteAnimation={onComplete}
/>
)}
</section>
{walletSelectorModalOpen &&
source.onChangeWallet &&
source.availableWallets && (
<SelectWalletModal
availableWallets={source.availableWallets}
onClose={() => setWalletSelectorModalOpen(false)}
onConnect={source.onChangeWallet}
/>
)}
{assetSelectorModalOpen &&
source.onChangeSelectedAsset &&
source.wallet &&
source.walletAddress && (
<SelectAssetModal
onClose={() => setAssetSelectorModalOpen(false)}
assets={sortedAssets}
onSelect={source.onChangeSelectedAsset}
wallet={source.wallet}
walletAddress={source.walletAddress}
/>
)}
{sourceChainModalOpen && source.onChangeChain && source.wallet && (
<SelectChainModal
onClose={() => setSourceChainModalOpen(false)}
chains={source.availableChains || []}
onSelect={source.onChangeChain}
wallet={source.wallet}
walletAddress={source.walletAddress}
/>
)}
{destinationChainModalOpen &&
destination.onChangeChain &&
destination.wallet && (
<SelectChainModal
onClose={() => setDestinationChainModalOpen(false)}
chains={destination.availableChains || []}
onSelect={destination.onChangeChain}
wallet={destination.wallet}
walletAddress={destination.walletAddress}
/>
)}
</>
);
};