forked from Pi-Defi-world/acbu-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage.tsx
More file actions
406 lines (380 loc) · 14.4 KB
/
Copy pathpage.tsx
File metadata and controls
406 lines (380 loc) · 14.4 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
"use client";
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Burn Tokens | ACBU',
description: 'Burn ACBU tokens to redeem fiat currency. Convert your digital assets back to traditional money.',
};
import React, { useState, Suspense } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { PageContainer } from "@/components/layout/page-container";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ArrowLeft, CheckCircle } from "lucide-react";
import { useApiOpts } from "@/hooks/use-api";
import { useApiError } from "@/hooks/use-api-error";
import { ApiErrorDisplay } from "@/components/ui/api-error-display";
import * as burnApi from "@/lib/api/burn";
import type { BurnRecipientAccount } from "@/types/api";
import { useAuth } from "@/contexts/auth-context";
import { useStellarWalletsKit } from "@/lib/stellar-wallets-kit";
import { getWalletSecretAnyLocal } from "@/lib/wallet-storage";
import { Keypair } from "@stellar/stellar-sdk";
import { submitBurnRedeemSingleClient } from "@/lib/stellar/burning";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
const burnSchema = z.object({
acbuAmount: z
.string()
.refine((val: string) => !isNaN(parseFloat(val)) && parseFloat(val) > 0, {
message: "Amount must be greater than 0",
}),
currency: z.string().length(3, "Currency must be exactly 3 uppercase letters"),
accountNumber: z
.string()
.min(5, "Account number is too short")
.max(20, "Account number is too long")
.regex(/^\d+$/, "Account number must contain only digits"),
bankCode: z
.string()
.min(3, "Bank code is too short")
.max(10, "Bank code is too long")
.regex(/^[A-Za-z0-9]+$/, "Bank code must be alphanumeric"),
accountName: z.string().min(3, "Account name is too short").max(100, "Account name is too long"),
});
type BurnFormValues = z.infer<typeof burnSchema>;
const formatCurrency = (amount: string, currency: string) => {
const value = parseFloat(amount);
if (isNaN(value)) return "";
try {
return new Intl.NumberFormat(navigator.language || 'en-US', {
style: "currency",
currency,
}).format(value);
} catch {
return `${value} ${currency}`;
}
};
function BurnPageContent() {
const opts = useApiOpts();
const searchParams = useSearchParams();
const { userId, stellarAddress } = useAuth();
const kit = useStellarWalletsKit();
const { uiError, setApiError, clearError, isSubmitDisabled } = useApiError();
const [loading, setLoading] = useState(false);
const [txId, setTxId] = useState<string | null>(null);
const form = useForm<BurnFormValues>({
resolver: zodResolver(burnSchema),
defaultValues: {
acbuAmount: searchParams?.get("amount") || "",
currency: (searchParams?.get("currency") || "NGN").toUpperCase().slice(0, 3),
accountNumber: "",
bankCode: "",
accountName: "",
},
mode: "onChange",
});
const { isValid } = form.formState;
const currency = form.watch("currency");
const onSubmit = async (values: BurnFormValues) => {
clearError();
setLoading(true);
setTxId(null);
try {
if (!userId) throw new Error("Not signed in");
if (!stellarAddress) throw new Error("No linked Stellar wallet address.");
const recipientAccount: BurnRecipientAccount = {
account_number: values.accountNumber.trim(),
bank_code: values.bankCode.trim(),
account_name: values.accountName.trim(),
type: "bank",
};
const secret = await getWalletSecretAnyLocal(userId, stellarAddress);
let burnTxHash: string;
if (secret) {
const localPubKey = Keypair.fromSecret(secret).publicKey();
if (stellarAddress && localPubKey !== stellarAddress) {
throw new Error(
`Local wallet (${localPubKey.slice(0, 6)}…${localPubKey.slice(-4)}) doesn't match the account on record (${stellarAddress.slice(0, 6)}…${stellarAddress.slice(-4)}). Re-import the correct seed from Settings, or update the wallet address, then retry.`,
);
}
const submit = await submitBurnRedeemSingleClient({
userAddress: stellarAddress,
amountAcbu: values.acbuAmount,
currency: values.currency,
userSecret: secret,
});
burnTxHash = submit.transactionHash;
} else {
if (!kit) {
throw new Error(
"Your wallet secret isn't available on this device and the wallet connector isn't ready yet. Please wait a moment and retry.",
);
}
const address = await new Promise<string>((resolve, reject) => {
kit
.openModal({
onWalletSelected: async (selectedOption: { id: string }) => {
try {
kit.setWallet(selectedOption.id);
const { address } = await kit.getAddress();
resolve(address);
} catch (err) {
reject(err);
}
const submit = await submitBurnRedeemSingleClient({
userAddress: stellarAddress,
amountAcbu: values.acbuAmount,
currency: values.currency,
userSecret: secret,
});
burnTxHash = submit.transactionHash;
} else {
if (!kit) throw new Error("Wallet connector not ready");
const address = await new Promise<string>((resolve, reject) => {
kit
.openModal({
onWalletSelected: async (selectedOption: { id: string }) => {
try {
kit.setWallet(selectedOption.id);
const { address } = await kit.getAddress();
resolve(address);
} catch (err) {
reject(err);
}
},
})
.catch(reject);
});
if (stellarAddress && address !== stellarAddress) {
throw new Error("Connected wallet doesn't match linked account");
}
const submit = await submitBurnRedeemSingleClient({
userAddress: stellarAddress,
amountAcbu: values.acbuAmount,
currency: values.currency,
external: { kit, address },
});
burnTxHash = submit.transactionHash;
}
const res = await burnApi.burnAcbu(values.acbuAmount, values.currency, recipientAccount, opts, burnTxHash);
setTxId(res.transaction_id);
reset({ ...values, acbuAmount: "" });
} catch (e) {
setApiError(e);
} finally {
setLoading(false);
}
const submit = await submitBurnRedeemSingleClient({
userAddress: stellarAddress,
amountAcbu: values.acbuAmount,
currency: values.currency,
external: { kit, address },
});
burnTxHash = submit.transactionHash;
}
const res = await burnApi.burnAcbu(
values.acbuAmount,
values.currency,
recipientAccount,
opts,
burnTxHash,
);
setTxId(res.transaction_id);
form.reset({ ...values, acbuAmount: "" });
} catch (e) {
setApiError(e);
} finally {
setLoading(false);
}
};
const currency = form.watch("currency");
return (
<>
<div className="page-header">
<div className="page-header-row">
<Link
href="/mint"
aria-label="Go back to Mint page"
className="touch-target"
>
<ArrowLeft className="w-5 h-5 text-primary" />
</Link>
<h1 className="page-title">Withdraw (Burn)</h1>
</div>
</div>
<PageContainer>
<Card className="border-border p-4 space-y-4">
<p className="text-muted-foreground text-sm">
Burn ACBU and withdraw to your bank or mobile money account.
</p>
{uiError && (
<ApiErrorDisplay error={uiError} onDismiss={clearError} />
)}
{txId && (
<div className="bg-green-500/10 border border-green-500/20 rounded-lg p-3 flex items-start gap-2">
<CheckCircle className="w-4 h-4 text-green-600 shrink-0 mt-0.5" />
<p className="text-green-600 text-sm font-medium">
Transaction submitted successfully! ID: {txId}
</p>
</div>
)}
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="acbuAmount"
render={({ field }: { field: any }) => (
<FormItem>
<FormLabel>ACBU amount</FormLabel>
<FormControl>
<Input
type="number"
placeholder="0.00"
min="0"
step="any"
{...field}
className="border-border"
/>
</FormControl>
{field.value && (
<p className="text-sm text-muted-foreground mt-1">
≈ {formatCurrency(field.value, currency)}
</p>
)}
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="currency"
render={({ field }: { field: any }) => (
<FormItem>
<FormLabel>Currency (3 letters)</FormLabel>
<FormControl>
<Input
placeholder="NGN"
{...field}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
const val = e.target.value.toUpperCase().slice(0, 3);
field.onChange(val);
}}
className="border-border"
maxLength={3}
/>
</FormControl>
<FormDescription>
The target currency for your withdrawal (e.g., NGN, KES).
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="accountNumber"
render={({ field }: { field: any }) => (
<FormItem>
<FormLabel>Account number</FormLabel>
<FormControl>
<Input
type="text"
inputMode="numeric"
placeholder="1234567890"
{...field}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
const val = e.target.value.replace(/\D/g, "");
field.onChange(val);
}}
className="border-border"
maxLength={20}
/>
</FormControl>
<FormDescription>
{currency === "NGN" ? "Nigerian bank accounts are typically 10 digits." : "Standard bank account number."}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="bankCode"
render={({ field }: { field: any }) => (
<FormItem>
<FormLabel>Bank code</FormLabel>
<FormControl>
<Input
type="text"
placeholder="Enter bank code"
{...field}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
const val = e.target.value.toUpperCase().slice(0, 10);
field.onChange(val);
}}
className="border-border"
maxLength={10}
/>
</FormControl>
<FormDescription>
Sort code, SWIFT/BIC, or local bank routing code.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="accountName"
render={({ field }: { field: any }) => (
<FormItem>
<FormLabel>Account name</FormLabel>
<FormControl>
<Input
type="text"
placeholder="John Doe"
{...field}
className="border-border"
maxLength={100}
/>
</FormControl>
<FormDescription>
The official name registered with the bank.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button
type="submit"
disabled={!isValid || loading || isSubmitDisabled}
className="w-full"
>
{loading ? "Submitting..." : "Burn & Withdraw"}
</Button>
</form>
</Form>
</Card>
</PageContainer>
</>
);
}
export default function BurnPage() {
return (
<Suspense fallback={<BurnPageSkeleton />}>
<BurnPageContent />
</Suspense>
);
}