-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathRenewBondDialog.tsx
More file actions
503 lines (459 loc) · 20.3 KB
/
Copy pathRenewBondDialog.tsx
File metadata and controls
503 lines (459 loc) · 20.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
import { useState, useMemo } from 'react'
import {
directsendMutation,
freezeMutation,
gettimelockaddressOptions,
} from '@joinmarket-webui/joinmarket-api-ts/@tanstack/react-query'
import type { DirectSendResponse, ErrorMessage } from '@joinmarket-webui/joinmarket-api-ts/jm'
import { useMutation, useQuery } from '@tanstack/react-query'
import {
AlertTriangleIcon,
CalendarIcon,
CheckCircle2Icon,
CheckIcon,
ChevronLeftIcon,
CopyIcon,
RefreshCwIcon,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { buttonVariants } from '@/components/ui/button-variants'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { CopyButton } from '@/components/ui/jam/CopyButton'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Spinner } from '@/components/ui/spinner'
import { Switch } from '@/components/ui/switch'
import { useJamWalletInfoContext } from '@/context/JamWalletInfoContext'
import { useApiClient } from '@/hooks/useApiClient'
import type { FidelityBondUtxo, Utxo } from '@/hooks/useQueryUtxos'
import { getErrorReason } from '@/lib/errorReason'
import * as fb from '@/lib/fidelityBondUtils'
import { cn, formatSats, type WalletFileName } from '@/lib/utils'
import { useDeveloperMode } from '@/store/jamSettingsStore'
import { getJarBadgeVariant } from '../ui/badge-variants'
import { Address } from '../ui/jam/Address'
import { generateLockdateOptions, getYearOptions, getMonthOptions } from './CreateFidelityBondDialog/types'
type Step = 'select_date' | 'confirm' | 'sending' | 'success'
interface RenewBondDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
walletFileName: WalletFileName
utxo: FidelityBondUtxo
}
export function RenewBondDialog({ open, onOpenChange, walletFileName, utxo }: RenewBondDialogProps) {
const { t } = useTranslation()
const client = useApiClient()
const walletInfo = useJamWalletInfoContext()
const { enabled: isDeveloperMode } = useDeveloperMode()
const [step, setStep] = useState<Step>('select_date')
const [selectedLockdate, setSelectedLockdate] = useState<fb.Lockdate | ''>('')
const [confirmationChecked, setConfirmationChecked] = useState(false)
const [txResult, setTxResult] = useState<DirectSendResponse | undefined>()
const [error, setError] = useState<string | undefined>()
const lockdateOptions = useMemo(() => generateLockdateOptions(isDeveloperMode), [isDeveloperMode])
const yearOptions = useMemo(() => getYearOptions(lockdateOptions), [lockdateOptions])
const monthOptions = useMemo(() => getMonthOptions(), [])
const minLockdate = lockdateOptions.at(0)?.value ?? ''
const maxLockdate = lockdateOptions.at(-1)?.value ?? ''
const clampLockdate = (lockdate: string): fb.Lockdate | '' => {
if (!lockdate || lockdate < minLockdate) return minLockdate || ''
if (lockdate > maxLockdate) return maxLockdate || ''
return lockdate as fb.Lockdate
}
const selectedYear = selectedLockdate ? selectedLockdate.slice(0, 4) : ''
const selectedMonth = selectedLockdate ? selectedLockdate.slice(5, 7) : ''
const minYear = minLockdate ? Number.parseInt(minLockdate.slice(0, 4), 10) : 0
const minMonth = minLockdate ? Number.parseInt(minLockdate.slice(5, 7), 10) : 1
const selectedDateLabel = selectedLockdate
? new Date(fb.lockdate.toTimestamp(selectedLockdate)).toLocaleDateString(undefined, {
year: 'numeric',
month: 'long',
day: 'numeric',
})
: null
const sourceJar = walletInfo.jars.find((jar) => jar.jarIndex === utxo.mixdepth)
// UTXOs in the source jar that are NOT this FB — they need to be frozen during sweep
const utxosToFreeze = useMemo(() => {
if (!sourceJar) return []
return sourceJar.utxos.filter((u) => u.utxo !== utxo.utxo && !u.frozen)
}, [sourceJar, utxo.utxo])
const timelockAddressQuery = useQuery({
...gettimelockaddressOptions({
client,
path: {
walletname: walletFileName,
lockdate: selectedLockdate || '',
},
}),
enabled: open && !!selectedLockdate && step !== 'select_date',
staleTime: Number.POSITIVE_INFINITY,
retry: false,
})
if (timelockAddressQuery.isError && !error) {
setError(t('earn.fidelity_bond.error_loading_address'))
}
const destinationAddress = timelockAddressQuery.data?.address
const freezeUtxo = useMutation({
...freezeMutation({ client }),
onError: (error: ErrorMessage) => {
const reason = getErrorReason(error, t('global.errors.reason_unknown'))
setError(`${t('earn.fidelity_bond.error_freezing_utxos')} ${reason}`)
},
})
const unfreezeUtxo = useMutation({
...freezeMutation({ client }),
onError: (error: ErrorMessage) => {
const reason = getErrorReason(error, t('global.errors.reason_unknown'))
setError(`${t('earn.fidelity_bond.error_unfreezing_utxos')} ${reason}`)
},
})
const directSend = useMutation({
...directsendMutation({ client }),
onError: (error: ErrorMessage) => {
const reason = getErrorReason(error, t('global.errors.reason_unknown'))
setError(`${t('earn.fidelity_bond.renew.error_renewing_fidelity_bond')} ${reason}`)
},
})
const handleReset = () => {
setStep('select_date')
setSelectedLockdate('')
setConfirmationChecked(false)
setTxResult(undefined)
setError(undefined)
}
const handleOpenChange = (newOpen: boolean) => {
if (!newOpen) {
handleReset()
}
onOpenChange(newOpen)
}
const handleSubmit = async () => {
if (!destinationAddress) return
setStep('sending')
setError(undefined)
const frozen: Utxo[] = []
try {
// Freeze other UTXOs in the source jar so only the FB gets swept
for (const u of utxosToFreeze) {
await freezeUtxo.mutateAsync({
path: { walletname: walletFileName },
body: { 'utxo-string': u.utxo, freeze: true },
})
frozen.push(u)
}
if (utxo.frozen) {
await unfreezeUtxo.mutateAsync({
path: { walletname: walletFileName },
body: { 'utxo-string': utxo.utxo, freeze: false },
})
}
const result = await directSend.mutateAsync({
path: { walletname: walletFileName },
body: {
mixdepth: utxo.mixdepth,
amount_sats: 0,
destination: destinationAddress,
},
})
setTxResult(result)
setStep('success')
toast.success(t('earn.fidelity_bond.renew.success_text'))
// Best-effort cleanup — tx already broadcast, don't throw on unfreeze failure
for (const u of frozen) {
try {
await unfreezeUtxo.mutateAsync({
path: { walletname: walletFileName },
body: { 'utxo-string': u.utxo, freeze: false },
})
} catch {
// logged via onError
}
}
await walletInfo.refetch()
} catch {
// Best-effort rollback — unfreeze UTXOs that were frozen before the error
for (const u of frozen) {
try {
await unfreezeUtxo.mutateAsync({
path: { walletname: walletFileName },
body: { 'utxo-string': u.utxo, freeze: false },
})
} catch {
// logged via onError
}
}
setStep('confirm')
}
}
const isLoading = freezeUtxo.isPending || unfreezeUtxo.isPending || directSend.isPending
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-h-[90dvh] max-w-lg overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-2xl">{t('earn.fidelity_bond.renew.title')}</DialogTitle>
<DialogDescription>{t('earn.fidelity_bond.subtitle')}</DialogDescription>
</DialogHeader>
{error && (
<Alert variant="destructive" className="animate-in fade-in-50">
<AlertTriangleIcon className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="py-2">
{step === 'select_date' && (
<div className="space-y-6">
<div className="bg-muted/50 flex items-center gap-3 rounded-lg p-4">
<div className="bg-primary/10 rounded-lg p-2">
<CalendarIcon className="text-primary h-5 w-5" />
</div>
<div className="flex-1">
<p className="font-medium">{t('earn.fidelity_bond.select_date.description')}</p>
</div>
</div>
<div className="bg-muted/50 rounded-lg p-4">
<p className="text-muted-foreground mb-1 text-xs">
{t('earn.fidelity_bond.review_inputs.label_amount')}
</p>
<p className="font-mono text-lg font-bold">{formatSats(utxo.value)}</p>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="renew-lockdate-month" className="text-sm font-medium">
{t('earn.fidelity_bond.select_date.form_label_month')}
</Label>
<Select
value={selectedMonth}
onValueChange={(month) => {
const year =
selectedYear || String(Number.parseInt(month, 10) >= minMonth ? minYear : minYear + 1)
const newLockdate = clampLockdate(`${year}-${month}`)
setSelectedLockdate(newLockdate)
}}
>
<SelectTrigger id="renew-lockdate-month" className="h-11 w-full">
<SelectValue placeholder={t('earn.fidelity_bond.select_date.form_label_month')} />
</SelectTrigger>
<SelectContent>
{monthOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="renew-lockdate-year" className="text-sm font-medium">
{t('earn.fidelity_bond.select_date.form_label_year')}
</Label>
<Select
value={selectedYear}
onValueChange={(year) => {
const month = selectedMonth || String(year === String(minYear) ? minMonth : 1).padStart(2, '0')
const newLockdate = clampLockdate(`${year}-${month}`)
setSelectedLockdate(newLockdate)
}}
>
<SelectTrigger id="renew-lockdate-year" className="h-11 w-full">
<SelectValue placeholder={t('earn.fidelity_bond.select_date.form_label_year')} />
</SelectTrigger>
<SelectContent>
{yearOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{selectedLockdate && (
<div className="bg-primary/5 border-primary/20 rounded-lg border p-4">
<p className="text-muted-foreground text-sm">
{t('earn.fidelity_bond.review_inputs.label_lock_date')}
</p>
<p className="mt-1 text-lg font-semibold">{selectedDateLabel}</p>
</div>
)}
</div>
)}
{step === 'confirm' && (
<div className="space-y-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="bg-muted/50 rounded-lg p-3">
<p className="text-muted-foreground text-xs">
{t('earn.fidelity_bond.review_inputs.label_lock_date')}
</p>
<p className="font-semibold">{selectedDateLabel}</p>
</div>
<div className="bg-muted/50 rounded-lg p-3">
<p className="text-muted-foreground text-xs">{t('earn.fidelity_bond.review_inputs.label_jar')}</p>
<Badge variant={getJarBadgeVariant(utxo.mixdepth)}>
{sourceJar?.name ?? t('earn.fidelity_bond.review_inputs.label_jar')} <span>#{utxo.mixdepth}</span>
</Badge>
</div>
</div>
<div className="bg-primary/5 border-primary/20 rounded-lg border p-3">
<p className="text-muted-foreground text-xs">{t('earn.fidelity_bond.review_inputs.label_amount')}</p>
<p className="font-mono text-2xl font-bold">{formatSats(utxo.value)}</p>
</div>
{timelockAddressQuery.isLoading ? (
<div className="text-muted-foreground flex items-center justify-center gap-2 py-4">
<Spinner className="motion-reduce:hidden" />
{t('earn.fidelity_bond.renew.text_loading')}
</div>
) : (
destinationAddress && (
<div className="space-y-2">
<Label className="text-sm font-medium">{t('earn.fidelity_bond.review_inputs.label_address')}</Label>
<div className="bg-muted rounded-lg p-3">
<Address className="text-xs" value={destinationAddress} />
</div>
</div>
)
)}
<Alert variant="warning">
<AlertTriangleIcon />
<AlertTitle>{t('earn.fidelity_bond.renew.confirm_send_modal.title')}</AlertTitle>
<AlertDescription>
{t('earn.fidelity_bond.confirm_modal.body', {
/* TODO: fix human readable duration */
humanReadableDuration: selectedDateLabel ? `until ${selectedDateLabel}` : '',
date: selectedDateLabel || '',
})}
</AlertDescription>
</Alert>
<div className="bg-muted/50 flex items-start gap-3 rounded-lg p-4">
<Switch
id="renew-confirmation"
checked={confirmationChecked}
onCheckedChange={(checked) => setConfirmationChecked(checked)}
/>
<div className="grid gap-1.5 leading-none">
<Label htmlFor="renew-confirmation" className="cursor-pointer text-sm font-medium">
{t('earn.fidelity_bond.create_form.confirmation_toggle_title')}
</Label>
<p className="text-muted-foreground text-xs">
{t('earn.fidelity_bond.create_form.confirmation_toggle_subtitle')}
</p>
</div>
</div>
</div>
)}
{step === 'sending' && (
<div className="flex flex-col items-center justify-center py-12">
<div className="relative">
<Spinner className="h-16 w-16" />
<div className="absolute inset-0 flex items-center justify-center">
<RefreshCwIcon className="text-primary h-6 w-6 animate-pulse" />
</div>
</div>
<p className="mt-6 text-lg font-semibold">{t('earn.fidelity_bond.renew.text_sending')}</p>
</div>
)}
{step === 'success' && (
<div className="space-y-6">
<div className="flex flex-col items-center py-6">
<div className="bg-brand-success/10 rounded-full p-4">
<CheckCircle2Icon className="text-brand-success h-16 w-16" />
</div>
<p className="mt-4 text-xl font-bold">{t('earn.fidelity_bond.renew.success_text')}</p>
</div>
{destinationAddress && (
<div className="space-y-2">
<Label className="text-sm font-medium">
{t('earn.fidelity_bond.create_fidelity_bond.label_address')}
</Label>
<div className="flex items-center gap-2">
<code className="bg-muted flex-1 rounded-lg p-3 font-mono text-xs break-all">
{destinationAddress}
</code>
<CopyButton
key="copy-address-renew"
value={destinationAddress}
text={<CopyIcon className="h-4 w-4" />}
successText={<CheckIcon className="text-brand-success h-4 w-4" />}
className={cn(buttonVariants({ variant: 'outline', size: 'icon' }), 'h-10 w-10 shrink-0')}
onSuccess={() => toast.success(t('receive.text_copy_address'))}
onError={() => toast.error(t('global.errors.reason_unknown'))}
/>
</div>
</div>
)}
{txResult?.txinfo?.txid && (
<div className="space-y-2">
<Label className="text-sm font-medium">
{t('earn.fidelity_bond.create_fidelity_bond.label_transaction_id')}
</Label>
<div className="flex items-center gap-2">
<code className="bg-muted flex-1 rounded-lg p-3 font-mono text-xs break-all">
{txResult.txinfo.txid}
</code>
<CopyButton
key="copy-txid-renew"
value={txResult.txinfo.txid}
text={<CopyIcon className="h-4 w-4" />}
successText={<CheckIcon className="text-brand-success h-4 w-4" />}
className={cn(buttonVariants({ variant: 'outline', size: 'icon' }), 'h-10 w-10 shrink-0')}
onSuccess={() =>
toast.success(t('earn.fidelity_bond.create_fidelity_bond.text_copy_transaction_id'))
}
onError={() => toast.error(t('global.errors.reason_unknown'))}
/>
</div>
</div>
)}
</div>
)}
</div>
{step === 'select_date' && (
<DialogFooter className="gap-3 sm:gap-2">
<Button variant="outline" className="min-w-24" onClick={() => handleOpenChange(false)}>
{t('earn.fidelity_bond.select_date.text_secondary_button')}
</Button>
<Button className="min-w-32" disabled={!selectedLockdate} onClick={() => setStep('confirm')}>
{t('earn.fidelity_bond.select_date.text_primary_button')}
</Button>
</DialogFooter>
)}
{step === 'confirm' && (
<DialogFooter className="gap-3 sm:gap-2">
<Button variant="ghost" onClick={() => setStep('select_date')} disabled={isLoading}>
<ChevronLeftIcon className="mr-1 h-4 w-4" />
{t('global.back')}
</Button>
<Button variant="outline" className="min-w-24" onClick={() => handleOpenChange(false)} disabled={isLoading}>
{t('earn.fidelity_bond.select_date.text_secondary_button')}
</Button>
<Button
className="min-w-32"
disabled={!confirmationChecked || !destinationAddress || isLoading}
onClick={() => void handleSubmit()}
>
{isLoading && <Spinner className="mr-2 h-4 w-4" />}
{t('earn.fidelity_bond.renew.text_button_submit')}
</Button>
</DialogFooter>
)}
{step === 'success' && (
<DialogFooter className="gap-3 sm:gap-2">
<Button className="min-w-32" onClick={() => handleOpenChange(false)}>
{t('earn.fidelity_bond.create_fidelity_bond.text_primary_button')}
</Button>
</DialogFooter>
)}
</DialogContent>
</Dialog>
)
}