forked from SmartDropLabs/smartdrop-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnlockModal.tsx
More file actions
553 lines (516 loc) · 19.3 KB
/
Copy pathUnlockModal.tsx
File metadata and controls
553 lines (516 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
"use client";
import {
poolContractId,
stellarNetwork,
} from "@/config";
import { useErrorHandler } from "@/context/ErrorContext";
import { useStellarWallet } from "@/context/StellarWalletContext";
import { useCountdown } from "@/hooks/useCountdown";
import { trackEvent } from "@/lib/analytics";
import {
stellarExpertTxUrl,
unlockAssets,
computePartialUnlockPreview,
getContractErrorMessage,
type UserPosition,
} from "@/lib/soroban";
import { QUERY_KEYS, useUnlockAssetsFeePreview } from "@/hooks/useSorobanQuery";
import { useFarmStore } from "@/store/farmStore";
import { unlockAvailableAt } from "@/types/farm";
import { useQueryClient } from "@tanstack/react-query";
import {
Alert,
AlertIcon,
Badge,
Box,
Button,
Flex,
Input,
Link,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalHeader,
ModalOverlay,
Spinner,
Text,
} from "@chakra-ui/react";
import { useEffect, useMemo, useRef, useState } from "react";
type UnlockStep =
| "idle"
| "simulating"
| "signing"
| "submitting"
| "confirming"
| "success"
| "timeout"
| "error";
const UNLOCK_STEP_LABEL: Record<UnlockStep, string> = {
idle: "",
simulating: "Simulating transaction...",
signing: "Waiting for Freighter signature...",
submitting: "Submitting transaction to Stellar...",
confirming: "Confirming transaction on Stellar...",
success: "Unlock confirmed",
timeout: "Confirmation is taking longer than expected.",
error: "Unlock failed",
};
export default function UnlockModal() {
const selectedPosition = useFarmStore((s) => s.selectedPosition);
const isUnlock = useFarmStore((s) => s.activeModal === "unlock");
const close = useFarmStore((s) => s.close);
const position = selectedPosition;
const { publicKey, walletApi, isNetworkMismatch } = useStellarWallet();
const toast = useErrorHandler();
const queryClient = useQueryClient();
const [amount, setAmount] = useState("");
const [step, setStep] = useState<UnlockStep>("idle");
const [error, setError] = useState<string | null>(null);
const [txHash, setTxHash] = useState<string | null>(null);
const amountInputRef = useRef<HTMLInputElement>(null);
const selectedPoolContractId = position?.contractAddress || poolContractId;
const unlockAt = position ? unlockAvailableAt(position) : 0;
const countdown = useCountdown(unlockAt);
const canUnlock = Boolean(position) && countdown.isElapsed;
const isProcessing =
step === "simulating" || step === "signing" || step === "submitting" || step === "confirming";
const numericAmount = Number(amount);
const amountValid =
Number.isFinite(numericAmount) &&
numericAmount >= 0.01 &&
!!position &&
numericAmount <= position.lockedAmount;
const feePreview = useUnlockAssetsFeePreview({
publicKey,
poolContractId: selectedPoolContractId,
amount: amountValid ? amount : "",
});
// Reset transient state whenever the modal opens for a (new) position.
useEffect(() => {
if (isUnlock && position) {
setAmount(String(position.lockedAmount));
setStep("idle");
setError(null);
setTxHash(null);
// Focus the amount input using a scoped ref instead of document.querySelector.
// Use a short delay to allow Chakra's Modal animation to complete.
setTimeout(() => {
amountInputRef.current?.focus();
amountInputRef.current?.select();
}, 100);
}
}, [isUnlock, position]);
const explorerUrl = useMemo(
() => (txHash ? stellarExpertTxUrl(txHash, stellarNetwork.toLowerCase()) : null),
[txHash]
);
if (!position) return null;
const handleClose = () => {
if (isProcessing) return;
close();
};
const setMax = () => setAmount(String(position.lockedAmount));
const set50Pct = () => setAmount(String(position.lockedAmount / 2));
const numericDailyRate = parseFloat(position.dailyRate) || 0;
const { remainingStake, newDailyRate } = computePartialUnlockPreview(
position.lockedAmount,
numericAmount,
numericDailyRate,
);
const handleUnlock = async () => {
if (!publicKey || !walletApi) {
setError("Connect your Freighter wallet to unlock.");
setStep("error");
return;
}
if (isNetworkMismatch) {
setError(`Switch Freighter to ${stellarNetwork} to unlock.`);
return;
}
if (!selectedPoolContractId) {
setError("Pool contract is not configured.");
setStep("error");
return;
}
if (!canUnlock) {
setError("Lock period has not elapsed yet.");
setStep("error");
return;
}
if (!amountValid) {
setError(`Enter an amount between 0.01 and ${position.lockedAmount}.`);
setStep("error");
return;
}
// Additional validation for minimum unlock amount
if (numericAmount < 0.01) {
setError("Minimum unlock amount is 0.01.");
setStep("error");
return;
}
setError(null);
setTxHash(null);
setStep("simulating");
const trackingStartTime = Date.now();
trackEvent("unlock_initiated", {
farm: position.name,
symbol: position.symbol,
amount: numericAmount,
partial: numericAmount < position.lockedAmount,
lockPeriodElapsed: canUnlock,
timeRemaining: countdown.remainingMs,
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : 'unknown',
});
// Snapshot the current position so we can rollback on failure.
const positionKey = [QUERY_KEYS.USER_POSITION, selectedPoolContractId, publicKey];
const previousPosition = queryClient.getQueryData<UserPosition>(positionKey);
// Optimistically reduce the locked amount in the cache so the UI
// reflects the unlock immediately, before the ledger confirms.
if (previousPosition) {
const prevAmount = Number(previousPosition.amount);
const unlockedAmount = Math.min(numericAmount, prevAmount);
const newAmount = Math.max(0, prevAmount - unlockedAmount);
queryClient.setQueryData<UserPosition>(positionKey, {
...previousPosition,
amount: String(newAmount),
isLocked: false,
unlockableAt: 0,
});
}
try {
const result = await unlockAssets({
poolContractId: selectedPoolContractId,
publicKey,
amount,
walletApi,
onHash: (hash) => setTxHash(hash),
onStep: (nextStep) => setStep(nextStep),
});
const hash = result.hash || result.transactionHash;
setTxHash(hash || null);
if (!result.success) {
// Roll back the optimistic update for definitive failures.
// On TIMEOUT the transaction may still land, so keep the
// optimistic state — the next refetch will correct it.
if (result.status !== "TIMEOUT" && previousPosition) {
queryClient.setQueryData<UserPosition>(positionKey, previousPosition);
}
const userMessage =
result.status === "TIMEOUT"
? "Confirmation is taking longer than expected. You can check the transaction manually on Stellar Expert."
: getContractErrorMessage(result.errorCode) ??
result.error ??
"Unlock transaction failed.";
setError(userMessage);
setStep(result.status === "TIMEOUT" ? "timeout" : "error");
trackEvent("unlock_failed", {
farm: position.name,
symbol: position.symbol,
amount: numericAmount,
reason: result.status ?? result.errorCode ?? "FAILED",
errorMessage: userMessage,
});
return;
}
setStep("success");
toast.success(
"Unlock Submitted",
`${numericAmount} ${position.symbol} unlock transaction submitted successfully`
);
trackEvent("unlock_succeeded", {
farm: position.name,
symbol: position.symbol,
amount: numericAmount,
hash,
partial: numericAmount < position.lockedAmount,
processingTime: Date.now() - trackingStartTime,
});
// Invalidate so the next refetch picks up the real ledger state
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.USER_POSITION, selectedPoolContractId] });
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.USER_POSITION, 'all', publicKey] });
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.USER_CREDITS, selectedPoolContractId] });
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.POOLS] });
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.PLATFORM_STATS] });
} catch (err) {
// Roll back the optimistic update on thrown errors
if (previousPosition) {
queryClient.setQueryData<UserPosition>(positionKey, previousPosition);
}
// Issue #250: let the user retry the same unlock straight from the
// error toast instead of having to reopen the modal and re-enter
// the amount.
const normalizedError = toast.handleError(err, "Unlock Transaction", () => void handleUnlock());
setError(normalizedError.userMessage);
setStep("error");
trackEvent("unlock_failed", {
farm: position.name,
symbol: position.symbol,
amount: numericAmount,
reason: normalizedError.code,
errorMessage: normalizedError.message,
});
}
};
const infoRow = (label: string, value: React.ReactNode) => (
<Flex justify="space-between" fontSize="sm" py={1}>
<Text color="app.muted">{label}</Text>
<Text>{value}</Text>
</Flex>
);
return (
<Modal isOpen={isUnlock} onClose={handleClose}>
<ModalOverlay backdropFilter="blur(3px)" />
<ModalContent
bg="app.surface"
color="app.text"
borderRadius="3xl"
mx={{ base: 4, md: "auto" }}
>
<ModalHeader mx="auto">Unlock {position.symbol}</ModalHeader>
<ModalCloseButton isDisabled={isProcessing} />
<ModalBody p={{ base: 4, md: 8 }}>
{step === "success" ? (
<Flex direction="column" gap={4} align="center" textAlign="center">
<Badge colorScheme="green" borderRadius="full" px={3} py={1}>
Unlock confirmed
</Badge>
<Text fontSize="sm" color="app.muted">
{numericAmount} {position.symbol} unlock transaction submitted successfully.
Your assets will be available in your wallet shortly.
</Text>
<Box
w="100%"
border="1px solid"
borderColor="app.border"
borderRadius="2xl"
p={3}
>
{infoRow(
"Remaining stake",
`${Math.max(0, position.lockedAmount - numericAmount)} ${
position.symbol
}`
)}
{explorerUrl &&
infoRow(
"Transaction",
<Link href={explorerUrl} isExternal color="app.accent">
View on Stellar Expert
</Link>
)}
</Box>
<Button
borderRadius="2xl"
w="full"
bg="app.accent"
color="app.onAccent"
_hover={{ opacity: 0.9 }}
onClick={handleClose}
>
Done
</Button>
</Flex>
) : (
<Flex direction="column" gap={6}>
<Box border="1px solid" borderColor="app.border" borderRadius="2xl" p={3}>
{infoRow(
"Amount locked",
`${position.lockedAmount} ${position.symbol}`
)}
{infoRow(
"Time remaining",
<Text color={canUnlock ? "app.accent" : "app.text"}>
{countdown.label}
</Text>
)}
{infoRow(
"Available to unlock",
`${canUnlock ? position.lockedAmount : 0} ${position.symbol}`
)}
</Box>
{!canUnlock && (
<Alert
status="warning"
borderRadius="2xl"
bg="app.warningBg"
color="app.warningFg"
fontSize="sm"
>
<AlertIcon color="app.warningFg" />
Assets are time-locked for security. You can unlock once the countdown
reaches zero to protect against impulsive withdrawals.
</Alert>
)}
<Flex direction="column" gap={2}>
<Text fontSize="2xs" color="app.muted">
Amount to unlock (partial allowed)
</Text>
<Box position="relative" w="100%">
<Input
ref={amountInputRef}
type="number"
borderRadius="2xl"
placeholder="Amount"
h="50px"
w="full"
pr="120px"
value={amount}
onChange={(e) => setAmount(e.target.value)}
isDisabled={!canUnlock || isProcessing}
borderColor="app.border"
bg="app.inputBg"
color="app.text"
_placeholder={{ color: "app.muted" }}
_hover={{ borderColor: "app.accent" }}
_focus={{ boxShadow: "none", borderColor: "app.accent" }}
/>
<Flex
position="absolute"
top="50%"
right="12px"
transform="translateY(-50%)"
gap={3}
align="center"
>
<Text fontSize="sm">{position.symbol}</Text>
<Text
fontSize="xs"
color="app.accent"
cursor={canUnlock ? "pointer" : "not-allowed"}
onClick={canUnlock ? set50Pct : undefined}
_hover={canUnlock ? { opacity: 0.8 } : {}}
transition="opacity 0.2s"
>
50%
</Text>
<Text
fontSize="xs"
color="app.accent"
cursor={canUnlock ? "pointer" : "not-allowed"}
onClick={canUnlock ? setMax : undefined}
_hover={canUnlock ? { opacity: 0.8 } : {}}
transition="opacity 0.2s"
>
Max
</Text>
</Flex>
</Box>
</Flex>
{!!amount && !amountValid && (
<Text fontSize="xs" color="#ff8080" role="alert">
{numericAmount < 0.01
? `Minimum unlock amount is 0.01 ${position.symbol}.`
: numericAmount > position.lockedAmount
? `Amount exceeds locked balance of ${position.lockedAmount} ${position.symbol}.`
: "Enter a valid amount."}
</Text>
)}
{amountValid && (
<Box border="1px solid #303030" borderRadius="2xl" p={3}>
{infoRow(
"Estimated receive",
`${numericAmount.toFixed(4)} ${position.symbol}`,
)}
{infoRow(
"Remaining stake",
`${remainingStake.toFixed(4)} ${position.symbol}`,
)}
{infoRow(
"New daily rate",
`${newDailyRate.toFixed(6)} credits/day`,
)}
{infoRow(
"Estimated Soroban fee",
feePreview.isFetching
? "Simulating..."
: feePreview.data
? `${feePreview.data.feePreview} stroops`
: "Unavailable",
)}
</Box>
)}
{isProcessing && (
<Alert status="info" borderRadius="2xl" bg="app.inputBg" color="app.text">
<Flex align="center" gap={3} w="full">
<Spinner size="sm" color="app.accent" />
<Box>
<Text fontSize="sm" fontWeight="semibold" aria-live="polite" aria-atomic="true">
{UNLOCK_STEP_LABEL[step]}
</Text>
{step === "confirming" && txHash && explorerUrl && (
<Link href={explorerUrl} isExternal color="app.accent" fontSize="sm">
View transaction on Stellar Expert
</Link>
)}
</Box>
</Flex>
</Alert>
)}
{step === "timeout" && (
<Alert status="warning" borderRadius="2xl" bg="app.warningBg" color="app.warningFg" aria-live="assertive" aria-atomic="true">
<AlertIcon color="app.warningFg" />
<Flex direction="column" gap={1}>
<Text>Confirmation is taking longer than expected.</Text>
{explorerUrl && (
<Link href={explorerUrl} isExternal color="app.accent">
Check the transaction on Stellar Expert
</Link>
)}
</Flex>
</Alert>
)}
{amountValid &&
!!position.minDepositAmount &&
remainingStake > 0 &&
remainingStake < position.minDepositAmount && (
<Alert
status="warning"
borderRadius="2xl"
bg="app.warningBg"
color="app.warningFg"
fontSize="sm"
>
<AlertIcon color="app.warningFg" />
Warning: remaining stake below minimum — the contract will close this position entirely
</Alert>
)}
{error && step !== "timeout" && (
<Alert
status="error"
borderRadius="2xl"
bg="app.errorBg"
color="app.errorFg"
fontSize="sm"
aria-live="assertive"
aria-atomic="true"
>
<AlertIcon color="app.errorFg" />
{error}
</Alert>
)}
<Button
borderRadius="2xl"
bg="app.accent"
color="app.onAccent"
_hover={{ opacity: 0.9 }}
isDisabled={!canUnlock || !amountValid || isProcessing || isNetworkMismatch}
onClick={() => void handleUnlock()}
w="full"
>
{isProcessing ? (
<Flex align="center" gap={2}>
<Spinner size="sm" />
<Text>{UNLOCK_STEP_LABEL[step]}</Text>
</Flex>
) : (
"Unlock with Freighter"
)}
</Button>
</Flex>
)}
</ModalBody>
</ModalContent>
</Modal>
);
}