-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtemp_diff.txt
More file actions
972 lines (941 loc) · 105 KB
/
Copy pathtemp_diff.txt
File metadata and controls
972 lines (941 loc) · 105 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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
diff --git a/app/marketplace/page.tsx b/app/marketplace/page.tsx
index 856f6d3..d1ac05d 100644
--- a/app/marketplace/page.tsx
+++ b/app/marketplace/page.tsx
@@ -1,9 +1,10 @@
"use client";
import { useState, useEffect, useCallback } from "react";
-import { Search, TrendingUp, Briefcase, Trash2, Loader2, AlertTriangle, ShieldCheck, X, Zap, Coins, Lock, ExternalLink, ChevronRight } from "lucide-react";
+import { Search, TrendingUp, Briefcase, Trash2, Loader2, AlertTriangle, ShieldCheck, X, Zap, Coins, Lock, ExternalLink, ChevronRight, Store } from "lucide-react";
import { useConnection, useWallet as useSolanaWallet } from "@solana/wallet-adapter-react";
import { useCredits } from "@/context/credits-context";
import { SystemProgram, Transaction, PublicKey, LAMPORTS_PER_SOL } from "@solana/web3.js";
+import { useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { CurrencyDisplay } from "@/components/ui/CurrencyDisplay";
@@ -30,52 +31,192 @@ interface AssetItem {
tokensAvailable?: number;
totalTokens?: number;
valuation?: number;
+ isListed?: boolean;
}
-// ÔöÇÔöÇÔöÇ Modal de Confirma├º├úo de Exclus├úo ÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇ
-function DeleteConfirmModal({
- assetName,
- onConfirm,
- onCancel,
- isDeleting,
-}: {
- assetName: string;
- onConfirm: () => void;
- onCancel: () => void;
- isDeleting: boolean;
-}) {
+// ÔöÇÔöÇÔöÇ Modal de Investimento Secund├írio ÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇ
+function SecondaryInvestModal({ receipt, onClose, onRefresh }: { receipt: any; onClose: () => void, onRefresh: () => void }) {
+ const { connection } = useConnection();
+ const { sendTransaction, publicKey } = useSolanaWallet();
+ const { solPrice, refreshSolPrice } = useCredits();
+ const router = useRouter();
+ const [isProcessing, setIsProcessing] = useState(false);
+
+ const asset = receipt.asset;
+ const resalePriceBRL = Number(receipt.resalePrice || 0);
+ const qty = receipt.quantity;
+ const originalCreatorWallet = asset.ownerWallet;
+
+ const totalBRLValue = qty * resalePriceBRL;
+ const totalBRL = totalBRLValue.toLocaleString("pt-BR", { style: "currency", currency: "BRL" });
+
+ // Royalties calculation (let's assume standard 2.5% for demo, or asset.royalties if exists)
+ const royaltiesPercent = 0.025;
+ const royaltiesBRL = totalBRLValue * royaltiesPercent;
+
return (
- <div className="fixed inset-0 z-[200] flex items-center justify-center">
- <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onCancel} />
- <div className="relative bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 p-8 animate-in zoom-in-95 fade-in duration-200">
- <div className="flex justify-center mb-4">
- <div className="w-14 h-14 rounded-full bg-red-100 flex items-center justify-center">
- <AlertTriangle className="w-7 h-7 text-red-600" />
+ <div className="fixed inset-0 z-[300] flex items-center justify-center p-4">
+ <div className="absolute inset-0 bg-slate-900/70 backdrop-blur-sm" onClick={onClose} />
+ <div className="relative bg-white rounded-3xl shadow-2xl max-w-lg w-full overflow-hidden animate-in zoom-in-95 fade-in duration-200">
+
+ <div className="relative w-full h-32 bg-amber-50 flex items-center justify-center overflow-hidden rounded-t-xl border-b border-amber-100 shrink-0">
+ <div className="absolute inset-0 flex flex-col justify-center items-center z-10 p-6">
+ <Store className="w-8 h-8 text-amber-500 mb-2" />
+ <h2 className="text-amber-900 text-2xl font-extrabold leading-tight text-center">Mercado Secundário</h2>
+ <p className="text-amber-700 text-xs font-bold uppercase tracking-widest mt-1">Compra de Lote Privado</p>
</div>
- </div>
- <h3 className="text-xl font-bold text-slate-900 text-center mb-2">Cancelar Simulação</h3>
- <p className="text-slate-500 text-center text-sm mb-2">
- Tem certeza que deseja cancelar e excluir permanentemente:
- </p>
- <p className="text-center font-semibold text-slate-800 mb-6">"{assetName}"</p>
- <p className="text-xs text-red-500 text-center mb-6 font-medium">
- ÔÜá´©Å Esta a├º├úo ├® irrevers├¡vel e n├úo pode ser desfeita.
- </p>
- <div className="flex gap-3">
- <button
- onClick={onCancel}
- disabled={isDeleting}
- className="flex-1 py-3 rounded-xl border border-slate-200 text-slate-700 font-semibold hover:bg-slate-50 transition-colors disabled:opacity-50"
- >
- Manter
+ <button onClick={onClose} className="absolute top-3 right-3 p-1.5 rounded-xl bg-black/10 hover:bg-black/20 text-black transition-colors z-10">
+ <X className="w-4 h-4" />
</button>
+ </div>
+
+ <div className="p-6 space-y-5">
+ <div className="text-center">
+ <h3 className="text-lg font-bold text-slate-800">{asset.name}</h3>
+ <p className="text-xs text-slate-500 mt-1">Vendedor: {receipt.investorWallet.slice(0, 4)}...{receipt.investorWallet.slice(-4)}</p>
+ </div>
+
+ <div className="grid grid-cols-2 gap-3">
+ <div className="bg-slate-50 border border-slate-200 rounded-2xl p-4 text-center">
+ <p className="text-xs text-slate-400 font-semibold uppercase tracking-wider mb-1">Preço Unitário</p>
+ <p className="text-xl font-extrabold text-slate-900 leading-none">
+ {resalePriceBRL.toLocaleString("pt-BR", { style: "currency", currency: "BRL" })}
+ </p>
+ </div>
+ <div className="bg-slate-50 border border-slate-200 rounded-2xl p-4 text-center">
+ <p className="text-xs text-slate-400 font-semibold uppercase tracking-wider mb-1">Lote Fechado</p>
+ <p className="text-xl font-extrabold text-slate-900 leading-none">{qty} Tokens</p>
+ </div>
+ </div>
+
+ <div className="bg-slate-50 border border-slate-200 rounded-2xl p-4">
+ <div className="flex justify-between items-center mb-2">
+ <span className="text-sm text-slate-500">Subtotal do Lote</span>
+ <span className="text-sm font-bold text-slate-800">{totalBRL}</span>
+ </div>
+ <div className="flex justify-between items-center mb-2">
+ <span className="text-xs text-slate-400 flex items-center gap-1"><ShieldCheck className="w-3 h-3"/> Royalties do Criador (2.5%)</span>
+ <span className="text-xs font-bold text-slate-600">{royaltiesBRL.toLocaleString("pt-BR", { style: "currency", currency: "BRL" })}</span>
+ </div>
+ </div>
+
+ <div className="bg-gradient-to-r from-violet-50 to-indigo-50 border border-violet-200 rounded-2xl p-4 flex items-start gap-3">
+ <div className="p-2 bg-violet-100 rounded-xl shrink-0">
+ <Coins className="w-5 h-5 text-violet-600" />
+ </div>
+ <div className="flex-1">
+ <p className="text-sm font-bold text-violet-800">Taxa Secundária Lake</p>
+ <p className="text-xs text-violet-600 mt-0.5">Esta transa├º├úo P2P consome <strong>5 Cr├®ditos Lake</strong> e <strong>$1.00 USD</strong> (em SOL).</p>
+ </div>
+ </div>
+
<button
- onClick={onConfirm}
- disabled={isDeleting}
- className="flex-1 py-3 rounded-xl bg-red-600 text-white font-semibold hover:bg-red-700 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
+ disabled={isProcessing}
+ onClick={async () => {
+ if (!publicKey) {
+ alert("Conecte sua carteira para comprar.");
+ return;
+ }
+ setIsProcessing(true);
+ try {
+ let currentPrice = solPrice;
+ if (!currentPrice || currentPrice <= 0) {
+ currentPrice = await refreshSolPrice();
+ }
+ if (!currentPrice || currentPrice <= 0) {
+ throw new Error("Falha ao obter cotação do SOL.");
+ }
+
+ // Valores em SOL
+ const sellerSol = totalBRLValue / currentPrice;
+ const platformSol = 1.00 / currentPrice;
+ const royaltiesSol = royaltiesBRL / currentPrice;
+
+ const SELLER_L = Math.floor(sellerSol * LAMPORTS_PER_SOL);
+ const PLATFORM_L = Math.floor(platformSol * LAMPORTS_PER_SOL);
+ const ROYALTIES_L = Math.floor(royaltiesSol * LAMPORTS_PER_SOL);
+
+ const treasuryPubKey = new PublicKey(process.env.NEXT_PUBLIC_TREASURY_WALLET_ADDRESS || "CXqfj7vFFrpBMVaj8fuyQkGwFgHktdyYVDju723hnmWa");
+ const sellerPubKey = new PublicKey(receipt.investorWallet);
+ const transaction = new Transaction();
+
+ // Instrução 1: Vendedor
+ transaction.add(
+ SystemProgram.transfer({
+ fromPubkey: publicKey,
+ toPubkey: sellerPubKey,
+ lamports: SELLER_L,
+ })
+ );
+
+ // Instrução 2: Tesouraria Lake
+ transaction.add(
+ SystemProgram.transfer({
+ fromPubkey: publicKey,
+ toPubkey: treasuryPubKey,
+ lamports: PLATFORM_L,
+ })
+ );
+
+ // Instrução 3: Criador (Royalties)
+ if (originalCreatorWallet && originalCreatorWallet !== receipt.investorWallet) {
+ const creatorPubKey = new PublicKey(originalCreatorWallet);
+ transaction.add(
+ SystemProgram.transfer({
+ fromPubkey: publicKey,
+ toPubkey: creatorPubKey,
+ lamports: ROYALTIES_L,
+ })
+ );
+ }
+
+ const latestBlockhash = await connection.getLatestBlockhash("confirmed");
+ transaction.recentBlockhash = latestBlockhash.blockhash;
+ transaction.feePayer = publicKey;
+
+ const signature = await sendTransaction(transaction, connection);
+
+ await connection.confirmTransaction({
+ signature,
+ blockhash: latestBlockhash.blockhash,
+ lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
+ }, "confirmed");
+
+ // Backend sync
+ const res = await fetch("/api/invest/secondary-buy", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ buyerWallet: publicKey.toBase58(),
+ receiptId: receipt.id,
+ transactionSignature: signature,
+ totalSolPaid: sellerSol + platformSol + royaltiesSol
+ }),
+ });
+
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error);
+
+ alert("Lote Secundário adquirido com sucesso! Verifique seu Dashboard do Investidor.");
+ onRefresh();
+ router.refresh();
+ onClose();
+
+ } catch (err: any) {
+ console.error("[SecondaryBuy]", err);
+ alert(`Erro na compra P2P: ${err.message}`);
+ } finally {
+ setIsProcessing(false);
+ }
+ }}
+ className="w-full py-4 bg-slate-900 hover:bg-slate-800 text-white font-extrabold rounded-xl text-lg flex items-center justify-center gap-2 transition-all shadow-lg hover:shadow-xl disabled:opacity-70 disabled:cursor-not-allowed"
>
- {isDeleting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
- {isDeleting ? "Excluindo..." : "Sim, Excluir"}
+ {isProcessing ? (
+ <Loader2 className="w-6 h-6 animate-spin" />
+ ) : (
+ <Store className="w-5 h-5" />
+ )}
+ {isProcessing ? "Processando Transação (0/2)..." : "Comprar Lote P2P"}
</button>
</div>
</div>
@@ -83,27 +224,24 @@ function DeleteConfirmModal({
);
}
-// ÔöÇÔöÇÔöÇ Modal de Investimento ÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇ
+// ÔöÇÔöÇÔöÇ Modal de Investimento Prim├írio ÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇ
function InvestModal({ asset, onClose }: { asset: AssetItem; onClose: () => void }) {
const { connection } = useConnection();
const { sendTransaction, publicKey } = useSolanaWallet();
const { solPrice, refreshSolPrice, addTransactionRecord } = useCredits();
+ const router = useRouter();
const [isProcessing, setIsProcessing] = useState(false);
- // Assumindo que o pre├ºo no banco j├í ├® a representa├º├úo base ou BRL
const tokenPriceBRL = asset.price ?? 0;
const maxQty = asset.tokensAvailable ?? 0;
const [qty, setQty] = useState(1);
- // Cota├º├Áes Fixas (Mock para Frontend Visual)
const RATE_USDC_BRL = 5.10;
const RATE_SOL_BRL = 850.0;
- // Cálculos Unitários
const tokenPriceUSDC = (tokenPriceBRL / RATE_USDC_BRL).toFixed(2);
const tokenPriceSOL = (tokenPriceBRL / RATE_SOL_BRL).toFixed(4);
- // Cálculos Totais
const totalBRLValue = qty * tokenPriceBRL;
const totalBRL = totalBRLValue.toLocaleString("pt-BR", { style: "currency", currency: "BRL" });
const totalUSDC = (totalBRLValue / RATE_USDC_BRL).toFixed(2);
@@ -114,80 +252,30 @@ function InvestModal({ asset, onClose }: { asset: AssetItem; onClose: () => void
<div className="absolute inset-0 bg-slate-900/70 backdrop-blur-sm" onClick={onClose} />
<div className="relative bg-white rounded-3xl shadow-2xl max-w-lg w-full overflow-hidden animate-in zoom-in-95 fade-in duration-200">
- {/* Hero image */}
{asset.image && asset.image.startsWith("https://") ? (
<div className="relative w-full h-48 bg-slate-50 flex items-center justify-center overflow-hidden rounded-t-xl border-b border-slate-100 shrink-0">
- <Image
- src={asset.image}
- alt="Asset RWA"
- fill
- className="object-contain p-4"
- />
- <div className="absolute inset-0 bg-gradient-to-t from-slate-900/40 via-transparent to-transparent pointer-events-none" />
- <div className="absolute bottom-4 left-5 z-10">
- <p className="text-white/90 text-xs font-bold uppercase tracking-widest drop-shadow-md">Ativo RWA Tokenizado</p>
- <h2 className="text-white text-2xl font-extrabold leading-tight drop-shadow-lg">{asset.name}</h2>
- </div>
- <div className="absolute top-3 left-3 px-2 py-1 rounded-lg bg-slate-900/80 backdrop-blur-sm text-[10px] font-bold text-white flex items-center gap-1 border border-white/10 z-10">
- <ShieldCheck className="w-3 h-3 text-emerald-400" /> Arweave RWA
- </div>
- <button onClick={onClose} className="absolute top-3 right-3 p-1.5 rounded-xl bg-black/40 hover:bg-black/60 text-white transition-colors z-10">
- <X className="w-4 h-4" />
- </button>
+ <Image src={asset.image} alt="Asset RWA" fill className="object-contain p-4" />
+ <button onClick={onClose} className="absolute top-3 right-3 p-1.5 rounded-xl bg-black/40 hover:bg-black/60 text-white transition-colors z-10"><X className="w-4 h-4" /></button>
</div>
) : (
<div className={`h-24 w-full ${asset.image} flex items-center px-6 justify-between`}>
- <div>
- <p className="text-white/70 text-xs font-bold uppercase tracking-widest">Ativo RWA</p>
- <h2 className="text-white text-xl font-extrabold">{asset.name}</h2>
- </div>
- <button onClick={onClose} className="p-1.5 rounded-xl bg-white/10 hover:bg-white/20 text-white transition-colors">
- <X className="w-4 h-4" />
- </button>
+ <div><h2 className="text-white text-xl font-extrabold">{asset.name}</h2></div>
+ <button onClick={onClose} className="p-1.5 rounded-xl bg-white/10 hover:bg-white/20 text-white transition-colors"><X className="w-4 h-4" /></button>
</div>
)}
- {/* Body */}
<div className="p-6 space-y-5">
- <div className="flex items-center gap-2 flex-wrap">
- <span className="px-3 py-1 bg-blue-50 text-blue-700 text-xs font-bold rounded-full border border-blue-100 uppercase tracking-wider">{asset.type}</span>
- <span className="px-3 py-1 bg-emerald-50 text-emerald-700 text-xs font-bold rounded-full border border-emerald-100">{asset.yield ?? "Rendimento variável"}</span>
- </div>
-
- {asset.description && (
- <section className="p-4 bg-slate-50 rounded-xl border border-slate-200">
- <h3 className="text-sm font-bold text-slate-800 uppercase tracking-wide mb-2">A Missão e o Lastro</h3>
- <p className="text-sm text-slate-600 leading-relaxed">{asset.description}</p>
- </section>
- )}
-
- {asset.valuation ? (
- <div className="flex items-center justify-between bg-slate-50 border border-slate-200 rounded-xl p-4">
- <span className="text-xs text-slate-500 font-semibold uppercase tracking-wider">Valuation do Empreendimento</span>
- <CurrencyDisplay variant="subtextOnly" brlValue={asset.valuation} />
- </div>
- ) : null}
-
- {/* Price grid */}
<div className="grid grid-cols-2 gap-3">
<div className="bg-slate-50 border border-slate-200 rounded-2xl p-4">
<p className="text-xs text-slate-400 font-semibold uppercase tracking-wider mb-1">Preço por Token</p>
- <p className="text-2xl font-extrabold text-slate-900 leading-none">
- {tokenPriceBRL.toLocaleString("pt-BR", { style: "currency", currency: "BRL" })}
- </p>
- <p className="text-xs text-slate-500 font-medium mt-1">
- ~ {tokenPriceUSDC} USDC | ~ {tokenPriceSOL} SOL
- </p>
+ <p className="text-2xl font-extrabold text-slate-900 leading-none">{tokenPriceBRL.toLocaleString("pt-BR", { style: "currency", currency: "BRL" })}</p>
</div>
<div className="bg-slate-50 border border-slate-200 rounded-2xl p-4 flex flex-col justify-center">
<p className="text-xs text-slate-400 font-semibold uppercase tracking-wider mb-1">Inventário</p>
- <p className="text-sm text-slate-700 mt-2">
- Disponível: <span className="font-bold">{asset.tokensAvailable?.toLocaleString() || "100%"}</span> de um total de {asset.totalTokens?.toLocaleString() || "100%"}
- </p>
+ <p className="text-sm text-slate-700 mt-2">Disponível: <span className="font-bold">{asset.tokensAvailable?.toLocaleString() || "100%"}</span></p>
</div>
</div>
- {/* Qty selector */}
<div className="bg-slate-50 border border-slate-200 rounded-2xl p-4">
<p className="text-xs text-slate-400 font-semibold uppercase tracking-wider mb-3">Quantidade de Tokens</p>
<div className="flex items-center gap-3">
@@ -199,103 +287,41 @@ function InvestModal({ asset, onClose }: { asset: AssetItem; onClose: () => void
<span className="text-sm text-slate-500 font-medium">Total estimado</span>
<div className="text-right">
<span className="block text-2xl font-extrabold text-slate-900 leading-none">{totalBRL}</span>
- <span className="block text-xs text-slate-500 font-medium mt-1">
- ~ {totalUSDC} USDC | ~ {totalSOL} SOL
- </span>
</div>
</div>
</div>
- {/* Taxa ÔÇö Motor de Cr├®ditos Lake */}
- <div className="bg-gradient-to-r from-violet-50 to-indigo-50 border border-violet-200 rounded-2xl p-4 flex items-start gap-3">
- <div className="p-2 bg-violet-100 rounded-xl shrink-0">
- <Coins className="w-5 h-5 text-violet-600" />
- </div>
- <div className="flex-1">
- <p className="text-sm font-bold text-violet-800">Taxa de Opera├º├úo ÔÇö Motor Lake</p>
- <p className="text-xs text-violet-600 mt-0.5">Esta opera├º├úo consome <strong>5 Cr├®ditos Lake</strong> e uma taxa de rede de <strong>$1.00 USD</strong> (convertidos em SOL) da sua carteira conectada.</p>
- </div>
- <div className="shrink-0 text-right">
- <p className="text-2xl font-extrabold text-violet-700">5</p>
- <p className="text-[10px] text-violet-500 font-bold uppercase">Cr├®ditos</p>
- </div>
- </div>
-
- {/* CTA */}
<button
onClick={async () => {
- if (!publicKey) {
- alert("Conecte sua carteira para investir.");
- return;
- }
-
+ if (!publicKey) return;
setIsProcessing(true);
try {
- console.log("[Invest] Preparando pagamento de investimento...");
-
- // 1. Obter Preço Dinâmico do SOL (US$)
let currentPrice = solPrice;
- if (!currentPrice || currentPrice <= 0) {
- currentPrice = await refreshSolPrice();
- }
-
- if (!currentPrice || currentPrice <= 0) {
- throw new Error("Falha ao obter cotação do SOL. Tente novamente.");
- }
+ if (!currentPrice || currentPrice <= 0) currentPrice = await refreshSolPrice();
+ if (!currentPrice || currentPrice <= 0) throw new Error("Falha ao obter cotação do SOL.");
- // Taxa da Plataforma: $1.00 USD
const exactFeeSol = 1.00 / currentPrice;
- const safeFeeSol = exactFeeSol * 1.01; // 1% buffer
- const INVEST_FEE = Math.floor(safeFeeSol * LAMPORTS_PER_SOL);
-
- // Custo Principal dos Tokens (P2P):
- const RATE_USDC_BRL = 5.10;
- const tokensUsdValue = ((asset.price || 0) * qty) / RATE_USDC_BRL;
- const exactTokensSol = tokensUsdValue / currentPrice;
- const safeTokensSol = exactTokensSol * 1.01; // 1% buffer
- const TOKENS_COST = Math.floor(safeTokensSol * LAMPORTS_PER_SOL);
-
- const totalSolAmount = safeFeeSol + safeTokensSol;
-
- const treasuryPubKey = new PublicKey(
- process.env.NEXT_PUBLIC_TREASURY_WALLET_ADDRESS || "CXqfj7vFFrpBMVaj8fuyQkGwFgHktdyYVDju723hnmWa"
- );
+ const PLATFORM_FEE_L = Math.floor(exactFeeSol * 1.01 * LAMPORTS_PER_SOL);
- if (publicKey.toBase58() === treasuryPubKey.toBase58()) {
- throw new Error("A carteira conectada não pode ser a própria Tesouraria.");
- }
+ const exactAssetSol = totalBRLValue / currentPrice;
+ const ASSET_COST_L = Math.floor(exactAssetSol * 1.01 * LAMPORTS_PER_SOL);
+ const totalSolAmount = (PLATFORM_FEE_L + ASSET_COST_L) / LAMPORTS_PER_SOL;
- const creatorPubKey = new PublicKey(asset.ownerWallet || treasuryPubKey.toBase58());
+ const treasuryPubKey = new PublicKey(process.env.NEXT_PUBLIC_TREASURY_WALLET_ADDRESS || "CXqfj7vFFrpBMVaj8fuyQkGwFgHktdyYVDju723hnmWa");
+ const ownerPubKey = new PublicKey(asset.ownerWallet || treasuryPubKey.toBase58());
- const transaction = new Transaction().add(
- // 1. Instrução de Taxa ($1.00 USD) para Tesouraria
- SystemProgram.transfer({
- fromPubkey: publicKey,
- toPubkey: treasuryPubKey,
- lamports: INVEST_FEE,
- }),
- // 2. Instrução Principal (Custo do Ativo) para o Criador (P2P)
- SystemProgram.transfer({
- fromPubkey: publicKey,
- toPubkey: creatorPubKey,
- lamports: TOKENS_COST,
- })
- );
+ const transaction = new Transaction();
+ transaction.add(SystemProgram.transfer({ fromPubkey: publicKey, toPubkey: treasuryPubKey, lamports: PLATFORM_FEE_L }));
+ transaction.add(SystemProgram.transfer({ fromPubkey: publicKey, toPubkey: ownerPubKey, lamports: ASSET_COST_L }));
const latestBlockhash = await connection.getLatestBlockhash("confirmed");
transaction.recentBlockhash = latestBlockhash.blockhash;
transaction.feePayer = publicKey;
const signature = await sendTransaction(transaction, connection);
- console.log("[Invest] Transação enviada. Assinatura:", signature);
-
- await connection.confirmTransaction({
- signature,
- blockhash: latestBlockhash.blockhash,
- lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
- }, "confirmed");
+
+ await connection.confirmTransaction({ signature, blockhash: latestBlockhash.blockhash, lastValidBlockHeight: latestBlockhash.lastValidBlockHeight }, "confirmed");
- // 2. Chamar Backend para Debitar Cr├®ditos e Registrar no Ledger
const res = await fetch("/api/invest", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -309,368 +335,207 @@ function InvestModal({ asset, onClose }: { asset: AssetItem; onClose: () => void
});
const data = await res.json();
- if (!res.ok) {
- throw new Error(data.error || "Falha ao registrar investimento no servidor.");
- }
+ if (!res.ok) throw new Error(data.error);
- // Update local history
- addTransactionRecord({
- id: Date.now().toString(),
- type: "USO",
- amount: "-5 Cr├®ditos",
- hash: signature,
- date: new Date().toLocaleString("pt-BR"),
- planId: `Investimento: ${asset.name}`,
- solAmount: totalSolAmount,
- });
-
- alert("ƒÄë Investimento simulado com sucesso!");
+ addTransactionRecord({ id: Date.now().toString(), type: "USO", amount: "-5 Cr├®ditos", hash: signature, date: new Date().toLocaleString("pt-BR"), planId: `Investimento: ${asset.name}`, solAmount: totalSolAmount });
+ alert("ƒÄë Investimento efetuado!");
+ router.refresh();
onClose();
+
} catch (err: any) {
- console.error("[Invest Error]", err);
- alert(`Falha no investimento: ${err.message}`);
+ alert(`Erro: ${err.message}`);
} finally {
setIsProcessing(false);
}
}}
- disabled={isProcessing}
- className="w-full py-4 bg-gradient-to-r from-slate-900 to-slate-800 hover:from-blue-700 hover:to-indigo-700 disabled:opacity-50 text-white font-extrabold rounded-2xl text-base transition-all duration-300 shadow-lg hover:shadow-blue-500/25 flex items-center justify-center gap-2 group"
+ className="w-full py-4 bg-slate-900 hover:bg-slate-800 text-white font-extrabold rounded-xl text-lg flex items-center justify-center gap-2 transition-all shadow-lg hover:shadow-xl"
>
- {isProcessing ? <Loader2 className="w-5 h-5 animate-spin" /> : <Zap className="w-5 h-5 group-hover:animate-pulse" />}
- {isProcessing ? "Processando Blockchain..." : "Confirmar Investimento"}
- {!isProcessing && <ChevronRight className="w-4 h-4 opacity-60 group-hover:translate-x-1 transition-transform" />}
+ {isProcessing ? <Loader2 className="w-6 h-6 animate-spin" /> : <TrendingUp className="w-5 h-5" />}
+ {isProcessing ? "Processando..." : "Confirmar Investimento"}
</button>
-
- <p className="text-center text-xs text-slate-400">
- Ao investir, você concorda com os Termos da LakeTokeniza e com a natureza simulada deste ativo na Devnet.
- </p>
</div>
</div>
</div>
);
}
-// ÔöÇÔöÇÔöÇ P├ígina Principal ÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇ
-export default function Marketplace() {
+// ÔöÇÔöÇÔöÇ Componente Principal ÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇ
+export default function MarketplacePage() {
+ const [activeFilter, setActiveFilter] = useState("Mercado Primário");
+ const [searchQuery, setSearchQuery] = useState("");
const { publicKey } = useSolanaWallet();
- const connectedWallet = publicKey?.toBase58() ?? null;
+ const connectedWallet = publicKey?.toBase58() || null;
- const [activeFilter, setActiveFilter] = useState("Todos");
const [assets, setAssets] = useState<AssetItem[]>(DEMO_ASSETS);
+ const [secondaryReceipts, setSecondaryReceipts] = useState<any[]>([]);
const [isLoadingAssets, setIsLoadingAssets] = useState(true);
- const [searchQuery, setSearchQuery] = useState("");
- // Estado do modal de exclusão
- const [deleteTarget, setDeleteTarget] = useState<AssetItem | null>(null);
- const [isDeleting, setIsDeleting] = useState(false);
const [investTarget, setInvestTarget] = useState<AssetItem | null>(null);
+ const [secondaryInvestTarget, setSecondaryInvestTarget] = useState<any | null>(null);
+ const [isCanceling, setIsCanceling] = useState<string | null>(null);
- // Busca ativos do banco de dados
- const fetchAssets = useCallback(async () => {
- setIsLoadingAssets(true);
+ const fetchPrimaryAssets = useCallback(async () => {
try {
- const url = connectedWallet
- ? `/api/assets?wallet=${connectedWallet}`
- : `/api/assets`;
-
+ const url = connectedWallet ? `/api/assets?wallet=${encodeURIComponent(connectedWallet)}` : `/api/assets`;
const res = await fetch(url);
const data = await res.json();
-
- if (res.ok && data.assets) {
- const dbAssets: AssetItem[] = data.assets.map((a: any) => {
- const isApproved = a.status === "APPROVED" || a.status === "ACTIVE" || a.status === "TOKENIZED";
- return {
- id: a.id,
- name: a.name,
- type: a.type,
- price: Number(a.tokenPrice) || Number(a.valuation) / 1000,
- yield: isApproved ? "12.0% a.a." : "Em Análise",
- available: "100%",
- image: a.imageUrl || "bg-slate-700",
- locked: isApproved ? false : true,
- isUserAsset: true,
- ownerWallet: a.ownerWallet,
- status: a.status,
- description: a.description || "Detalhes comerciais deste projeto em fase de estruturação.",
- tokensAvailable: a.marketTokens || 0,
- totalTokens: a.totalTokens || 0,
- valuation: Number(a.valuation) || 0,
- };
- });
-
+ if (data.assets) {
+ const dbAssets: AssetItem[] = data.assets.map((a: any) => ({
+ id: a.id, name: a.name, type: a.type, price: Number(a.tokenPrice) || Number(a.valuation) / 1000,
+ yield: "12.0% a.a.", available: "100%", image: a.imageUrl || "bg-slate-700", locked: false,
+ isUserAsset: true, ownerWallet: a.ownerWallet, status: a.status, description: a.description,
+ tokensAvailable: a.marketTokens || 0, totalTokens: a.totalTokens || 0, valuation: Number(a.valuation) || 0,
+ isListed: a.isListed !== false,
+ }));
setAssets([...dbAssets, ...DEMO_ASSETS]);
}
} catch (err) {
- console.error("[Marketplace] Erro ao buscar ativos:", err);
setAssets(DEMO_ASSETS);
} finally {
setIsLoadingAssets(false);
}
}, [connectedWallet]);
- useEffect(() => {
- fetchAssets();
- }, [fetchAssets]);
-
- // Exclusão com validação de autoria
- const handleDeleteConfirm = async () => {
- if (!deleteTarget || !connectedWallet) return;
-
- setIsDeleting(true);
+ const fetchSecondaryAssets = useCallback(async () => {
try {
- const res = await fetch(
- `/api/assets/${deleteTarget.id}?wallet=${encodeURIComponent(connectedWallet)}`,
- { method: "DELETE" }
- );
-
+ const res = await fetch('/api/marketplace/secondary');
const data = await res.json();
+ if (data.receipts) setSecondaryReceipts(data.receipts);
+ } catch (err) {}
+ }, []);
- if (!res.ok) throw new Error(data.error || "Erro ao excluir.");
+ useEffect(() => {
+ fetchPrimaryAssets();
+ fetchSecondaryAssets();
+ }, [fetchPrimaryAssets, fetchSecondaryAssets]);
- // Atualiza├º├úo imediata do estado local ÔÇö sem reload
- setAssets(prev => prev.filter(a => a.id !== deleteTarget.id));
- setDeleteTarget(null);
- } catch (e: any) {
- alert(`ÔØî ${e.message}`);
- } finally {
- setIsDeleting(false);
- }
- };
+ const isMyAsset = (owner: string | null) => connectedWallet !== null && owner === connectedWallet;
- // Forçar aprovação do ativo (Dev Mode)
- const handleForceApproval = async (assetId: string) => {
+ const handleCancelResale = async (receiptId: string) => {
if (!connectedWallet) return;
+ if (!window.confirm("Deseja retirar este lote do Mercado Secundário e devolvê-lo à sua carteira?")) return;
+
+ setIsCanceling(receiptId);
try {
- const res = await fetch(`/api/assets/${assetId}?wallet=${encodeURIComponent(connectedWallet)}`, {
- method: "PATCH",
+ const res = await fetch("/api/invest/cancel-resale", {
+ method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ status: "APPROVED" }),
+ body: JSON.stringify({ receiptId, walletAddress: connectedWallet })
});
-
const data = await res.json();
- if (!res.ok) throw new Error(data.error || "Erro ao aprovar ativo.");
-
- // Atualiza o estado local do ativo para aprovação imediata sem reload
- setAssets(prev =>
- prev.map(a =>
- a.id === assetId
- ? { ...a, status: "APPROVED", locked: false, yield: "12.0% a.a." }
- : a
- )
- );
- } catch (e: any) {
- alert(`ÔØî ${e.message}`);
+ if (!res.ok) throw new Error(data.error);
+
+ alert("Venda cancelada. O lote retornou ao seu Dashboard HELD.");
+ fetchSecondaryAssets();
+ } catch (err: any) {
+ alert(`Erro: ${err.message}`);
+ } finally {
+ setIsCanceling(null);
}
};
- const filteredAssets = assets
- .filter(a => {
- if (activeFilter === "Meus Ativos") return a.ownerWallet === connectedWallet;
- if (activeFilter !== "Todos") return a.type.includes(activeFilter);
- return true;
- })
- .filter(a =>
- searchQuery === "" ||
- a.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
- a.type.toLowerCase().includes(searchQuery.toLowerCase())
- );
-
- const isMyAsset = (a: AssetItem) =>
- connectedWallet !== null && a.ownerWallet === connectedWallet;
-
return (
<div className="min-h-screen bg-slate-50 text-slate-900 font-sans">
- {/* Header */}
<div className="bg-white border-b border-slate-200 pt-12 pb-8 px-6">
<h1 className="text-3xl font-bold">Marketplace</h1>
- <p className="text-slate-500 mt-1 text-sm">Ativos tokenizados e simula├º├Áes em an├ílise</p>
</div>
- {/* Filtros e Busca */}
<div className="sticky top-20 z-30 bg-slate-50/95 backdrop-blur-sm border-b border-slate-200 py-4 px-6 flex flex-wrap justify-between gap-3">
<div className="flex gap-2 flex-wrap">
- {["Todos", "Meus Ativos"].map(f => (
+ {["Mercado Primário", "Mercado Secundário", "Meus Ativos"].map(f => (
<button
key={f}
onClick={() => setActiveFilter(f)}
className={`px-4 py-2 rounded-full text-sm font-bold transition-all ${
- activeFilter === f
- ? "bg-slate-900 text-white shadow-md"
- : "bg-white border border-slate-200 hover:border-slate-400"
+ activeFilter === f ? "bg-slate-900 text-white shadow-md" : "bg-white border border-slate-200 hover:border-slate-400"
}`}
>
{f}
- {f === "Meus Ativos" && connectedWallet && (
- <span className="ml-2 bg-purple-100 text-purple-700 text-[10px] px-1.5 py-0.5 rounded-full font-bold">
- {assets.filter(a => a.ownerWallet === connectedWallet).length}
- </span>
- )}
</button>
))}
</div>
- <div className="relative w-64">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
- <input
- type="text"
- placeholder="Buscar ativo..."
- value={searchQuery}
- onChange={e => setSearchQuery(e.target.value)}
- className="w-full pl-10 pr-4 py-2 rounded-lg border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900"
- />
- </div>
</div>
- {/* Grid */}
<div className="container mx-auto px-6 py-12">
{isLoadingAssets ? (
- <div className="flex justify-center items-center py-24">
- <Loader2 className="w-8 h-8 animate-spin text-slate-400" />
- <span className="ml-3 text-slate-500">Carregando ativos...</span>
- </div>
- ) : filteredAssets.length === 0 ? (
- <div className="text-center py-24">
- <Briefcase className="w-12 h-12 text-slate-300 mx-auto mb-4" />
- <p className="text-slate-400 text-lg font-medium">Nenhum ativo encontrado.</p>
- {activeFilter === "Meus Ativos" && (
- <p className="text-slate-400 text-sm mt-1">Crie uma simulação no Simulador Institucional.</p>
- )}
- </div>
+ <div className="flex justify-center items-center py-24"><Loader2 className="w-8 h-8 animate-spin text-slate-400" /></div>
) : (
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
- {filteredAssets.map(asset => (
- <div
- key={asset.id}
- className="group bg-white border border-slate-200 rounded-xl overflow-hidden hover:shadow-xl transition-all duration-300"
- >
- {/* Capa do ativo ÔÇö cont├¬iner de altura fixa, imagem absolutamente posicionada */}
- {asset.image && asset.image.startsWith("https://") ? (
- <div className="relative w-full h-48 bg-slate-50 flex items-center justify-center overflow-hidden rounded-t-xl border-b border-slate-100 shrink-0">
- <Image
- src={asset.image}
- alt="Asset RWA"
- fill
- className="object-contain p-4"
- />
- <div className="absolute top-3 left-3 px-2 py-1 rounded bg-slate-900/80 backdrop-blur-sm text-[9px] font-bold text-white uppercase tracking-wider flex items-center gap-1 border border-white/10 z-10">
- <ShieldCheck className="w-3 h-3 text-emerald-400" />
- Arweave RWA
+
+ {activeFilter === "Mercado Primário" || activeFilter === "Meus Ativos" ? (
+ assets
+ .filter(a => {
+ if (activeFilter === "Meus Ativos") return a.ownerWallet === connectedWallet;
+ // No mercado primário público, mostrar apenas listados
+ if (a.isDemo) return true;
+ return a.isListed !== false;
+ })
+ .map(asset => (
+ <div key={asset.id} className="group bg-white border border-slate-200 rounded-xl overflow-hidden hover:shadow-xl transition-all duration-300 flex flex-col">
+ {asset.image && asset.image.startsWith("https://") ? (
+ <div className="relative w-full h-48 bg-slate-50 flex items-center justify-center overflow-hidden border-b border-slate-100">
+ <Image src={asset.image} alt="Asset" fill className="object-contain p-4" />
</div>
- </div>
- ) : (
- <div className={`h-2 w-full shrink-0 ${asset.image || "bg-slate-700"}`} />
- )}
-
- <div className="p-6">
- <div className="flex justify-between mb-4">
- <div className={`p-2 rounded-lg ${isMyAsset(asset) ? "bg-purple-50 text-purple-700" : "bg-blue-50 text-blue-700"}`}>
- {isMyAsset(asset) ? <Briefcase className="w-5 h-5" /> : <TrendingUp className="w-5 h-5" />}
+ ) : (
+ <div className={`h-2 w-full shrink-0 ${asset.image || "bg-slate-700"}`} />
+ )}
+ <div className="p-6 flex-1 flex flex-col">
+ <h3 className="text-lg font-bold mb-1 truncate">{asset.name}</h3>
+ <p className="text-xs text-slate-500 font-medium mb-4">{asset.type}</p>
+ <div className="grid grid-cols-2 gap-4 mb-6">
+ <div><p className="text-[10px] text-slate-400 font-bold uppercase">Preço</p><p className="font-extrabold text-slate-900">{(asset.price || 0).toLocaleString("pt-BR", { style: "currency", currency: "BRL" })}</p></div>
+ <div><p className="text-[10px] text-slate-400 font-bold uppercase">Rendimento</p><p className="font-extrabold text-emerald-600">{asset.yield}</p></div>
</div>
- <div className="flex items-center gap-2">
- {isMyAsset(asset) ? (
- asset.status === "APPROVED" || asset.status === "ACTIVE" || asset.status === "TOKENIZED" ? (
- <span className="px-2 py-1 rounded text-[10px] font-bold uppercase bg-emerald-100 text-emerald-800 flex items-center gap-1">
- <span className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse"></span>
- ATIVO
- </span>
- ) : (
- <span className="px-2 py-1 rounded text-[10px] font-bold uppercase bg-purple-100 text-purple-800">
- EM ANÁLISE
- </span>
- )
+ <div className="mt-auto">
+ {isMyAsset(asset.ownerWallet) ? (
+ <Link href={`/manage/${asset.id}`} className="w-full block text-center py-3 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-lg text-sm transition-colors shadow-sm">Gerenciar Ativo</Link>
) : (
- <span className="px-2 py-1 rounded text-[10px] font-bold uppercase bg-green-50 text-green-700 flex items-center gap-1">
- <span className="h-1.5 w-1.5 rounded-full bg-green-500"></span>
- ATIVO
- </span>
- )}
-
- {/* Bot├úo Destrutivo ÔÇö apenas para o dono */}
- {isMyAsset(asset) && !asset.isDemo && (
- <button
- onClick={() => setDeleteTarget(asset)}
- title="Cancelar esta simulação"
- className="p-1.5 rounded-lg text-red-400 hover:bg-red-50 hover:text-red-600 transition-colors"
- >
- <Trash2 className="w-4 h-4" />
- </button>
+ <button onClick={() => setInvestTarget(asset)} className="w-full py-3 bg-slate-900 hover:bg-slate-800 text-white font-bold rounded-lg text-sm transition-colors">Investir no Emissor</button>
)}
</div>
</div>
-
- <h3 className="text-lg font-bold mb-1 truncate" title={asset.name}>{asset.name}</h3>
- <p className="text-xs text-slate-500 uppercase mb-4 truncate">{asset.type}</p>
-
- {isMyAsset(asset) ? (
- asset.status === "APPROVED" || asset.status === "ACTIVE" || asset.status === "TOKENIZED" ? (
- <Link
- href={`/manage/${asset.id}`}
- className="block w-full py-2 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white rounded-lg font-bold text-sm text-center transition-all shadow-[0_0_15px_rgba(37,99,235,0.2)] hover:shadow-[0_0_20px_rgba(37,99,235,0.4)]"
- >
- Gerenciar Ativo
- </Link>
- ) : (
- <div className="flex gap-2">
- <Link
- href={`/manage/${asset.id}`}
- className="flex-grow py-2 bg-gradient-to-r from-indigo-600 to-blue-600 hover:from-indigo-700 hover:to-blue-700 text-white rounded-lg font-bold text-sm text-center transition-all shadow-md flex items-center justify-center"
- >
- Gerenciar (Modo Dev)
- </Link>
- <button
- onClick={() => handleForceApproval(asset.id)}
- className="px-4 py-2 bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-white rounded-lg text-xs font-bold transition-all shadow-sm flex items-center gap-1"
- title="Aprovar Ativo na Blockchain"
- >
- Aprovar
- </button>
- </div>
- )
- ) : (
- <button
- disabled={asset.locked}
- onClick={() => {
- if (!connectedWallet) {
- alert("Acesso Negado: Conecte sua carteira Web3 para visualizar a tese de investimento.");
- return;
- }
- if (!asset.locked) setInvestTarget(asset);
- }}
- className={`w-full py-2.5 rounded-xl font-bold text-sm transition-all duration-200 ${
- asset.locked
- ? "bg-slate-100 text-slate-400 cursor-default"
- : "bg-gradient-to-r from-slate-900 to-slate-800 hover:from-blue-700 hover:to-indigo-700 text-white shadow-sm hover:shadow-blue-500/20 flex items-center justify-center gap-1.5"
- }`}
- >
- {asset.locked ? (
- <span className="flex items-center gap-1.5 justify-center"><Lock className="w-3.5 h-3.5" /> Em Análise</span>
- ) : (
- <span className="flex items-center gap-1.5 justify-center"><Zap className="w-3.5 h-3.5" /> Investir</span>
- )}
- </button>
- )}
</div>
- </div>
- ))}
+ ))
+ ) : null}
+
+ {activeFilter === "Mercado Secundário" ? (
+ secondaryReceipts.length === 0 ? (
+ <div className="col-span-3 text-center py-20 text-slate-500 font-medium">Nenhum ativo listado no mercado secundário.</div>
+ ) : (
+ secondaryReceipts.map((receipt) => (
+ <div key={receipt.id} className="group bg-white border-2 border-amber-100 rounded-xl overflow-hidden hover:shadow-xl transition-all duration-300 flex flex-col">
+ <div className="bg-amber-50 py-3 px-4 flex justify-between items-center border-b border-amber-100">
+ <span className="text-xs font-bold text-amber-700 flex items-center gap-1"><Store className="w-3 h-3"/> Mercado Secundário</span>
+ <span className="text-[10px] text-amber-600/70 font-mono">P2P LOTE</span>
+ </div>
+ <div className="p-6 flex-1 flex flex-col">
+ <h3 className="text-lg font-bold mb-1 truncate">{receipt.asset.name}</h3>
+ <p className="text-xs text-slate-500 font-medium mb-4">Vendedor: {receipt.investorWallet.slice(0, 4)}...{receipt.investorWallet.slice(-4)}</p>
+ <div className="grid grid-cols-2 gap-4 mb-6 bg-slate-50 p-3 rounded-lg border border-slate-100">
+ <div><p className="text-[10px] text-slate-400 font-bold uppercase">Preço Unitário</p><p className="font-extrabold text-slate-900">{Number(receipt.resalePrice).toLocaleString("pt-BR", { style: "currency", currency: "BRL" })}</p></div>
+ <div><p className="text-[10px] text-slate-400 font-bold uppercase">Lote Ofertado</p><p className="font-extrabold text-indigo-600">{receipt.quantity} Tokens</p></div>
+ </div>
+ <div className="mt-auto">
+ {isMyAsset(receipt.investorWallet) ? (
+ <button onClick={() => handleCancelResale(receipt.id)} disabled={isCanceling === receipt.id} className="w-full py-3 bg-red-50 hover:bg-red-100 text-red-600 font-bold rounded-lg text-sm border border-red-200 transition-colors">
+ {isCanceling === receipt.id ? "Cancelando..." : "Cancelar Venda"}
+ </button>
+ ) : (
+ <button onClick={() => setSecondaryInvestTarget(receipt)} className="w-full py-3 bg-amber-500 hover:bg-amber-600 text-white font-bold rounded-lg text-sm transition-colors shadow-sm">Comprar Lote P2P</button>
+ )}
+ </div>
+ </div>
+ </div>
+ ))
+ )
+ ) : null}
+
</div>
)}
</div>
- {/* Modal de Confirmação de Exclusão */}
- {deleteTarget && (
- <DeleteConfirmModal
- assetName={deleteTarget.name}
- onConfirm={handleDeleteConfirm}
- onCancel={() => !isDeleting && setDeleteTarget(null)}
- isDeleting={isDeleting}
- />
- )}
-
- {investTarget && (
- <InvestModal
- asset={investTarget}
- onClose={() => setInvestTarget(null)}
- />
- )}
+ {investTarget && <InvestModal asset={investTarget} onClose={() => setInvestTarget(null)} />}
+ {secondaryInvestTarget && <SecondaryInvestModal receipt={secondaryInvestTarget} onClose={() => setSecondaryInvestTarget(null)} onRefresh={fetchSecondaryAssets} />}
</div>
);
}
\ No newline at end of file