-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-collection.txt
More file actions
10863 lines (9439 loc) · 334 KB
/
code-collection.txt
File metadata and controls
10863 lines (9439 loc) · 334 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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
================================================================================
File: .bolt/config.json
================================================================================
{
"template": "nextjs-shadcn"
}
================================================================================
File: app/api/auth/nonce/route.ts
================================================================================
import { NextResponse } from 'next/server';
import { storeNonce } from '@/lib/auth';
export async function POST(req: Request) {
try {
const { address } = await req.json();
const nonce = storeNonce(address);
return NextResponse.json({ nonce });
} catch (error) {
return NextResponse.json(
{ error: 'Failed to generate nonce' },
{ status: 500 }
);
}
}
================================================================================
File: app/api/auth/verify/route.ts
================================================================================
import { NextResponse } from 'next/server';
import { verifySignature, generateToken } from '@/lib/auth';
export async function POST(req: Request) {
try {
const { message, signature, address } = await req.json();
const user = await verifySignature(message, signature, address);
const token = generateToken(user);
return NextResponse.json({ token });
} catch (error) {
return NextResponse.json(
{ error: 'Authentication failed' },
{ status: 401 }
);
}
}
================================================================================
File: app/api/blockchain-query/route.ts
================================================================================
import { NextResponse } from 'next/server';
import { AgentOrchestrator } from '@/lib/orchestrator';
const corsHeaders = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
const orchestrator = new AgentOrchestrator();
export async function OPTIONS() {
return NextResponse.json({}, { headers: corsHeaders });
}
export async function POST(req: Request) {
try {
let body;
try {
body = await req.json();
} catch {
return NextResponse.json(
{ error: 'Invalid JSON in request body' },
{ status: 400, headers: corsHeaders }
);
}
const { query, sessionId } = body;
if (!query?.trim()) {
return NextResponse.json(
{ error: 'Query is required' },
{ status: 400, headers: corsHeaders }
);
}
const result = await orchestrator.processQuery(query, sessionId);
return NextResponse.json(result, {
status: 200,
headers: corsHeaders
});
} catch (error) {
console.error('API Error:', error);
return NextResponse.json(
{
error: error instanceof Error ? error.message : 'Failed to process request'
},
{ status: 500, headers: corsHeaders }
);
}
}
================================================================================
File: app/api/blockchain/route.ts
================================================================================
import { NextRequest, NextResponse } from 'next/server';
import { blockchainOrchestrator } from '@/lib/agents/blockchain-orchestrator';
import { BlockchainActionParams } from '@/lib/agents/blockchain-orchestrator';
import { sessionManager } from '@/lib/blockchain/session-manager';
import { WalletIntegrationService } from '@/lib/blockchain/wallet-integration';
import { USE_MOCKS } from '@/lib/blockchain/config';
export async function POST(request: NextRequest) {
console.log('Blockchain API Route: Request received');
try {
const body = await request.json();
const { action, sessionId } = body;
// Use default-session if sessionId is not provided
const effectiveSessionId = sessionId || 'default-session';
console.log('Blockchain API Route: Request body parsed', {
actionType: action?.actionType,
sessionId: effectiveSessionId,
originalSessionId: sessionId,
usingDefaultSession: !sessionId,
hasAction: !!action,
headers: Object.fromEntries(request.headers)
});
if (!action || !action.actionType) {
console.error('Blockchain API Route: Invalid request - missing actionType');
return NextResponse.json(
{ error: 'Invalid request: actionType is required' },
{ status: 400 }
);
}
// Special handling for wallet connections
if (action.actionType === 'CONNECT_WALLET') {
console.log('Blockchain API Route: Handling wallet connection', {
sessionId: effectiveSessionId,
provider: action.walletParams?.type,
forceRealWallet: action.walletParams?.forceRealWallet
});
// If forceRealWallet is set, skip the mock wallet creation
if (action.walletParams?.forceRealWallet) {
console.log('Blockchain API Route: forceRealWallet flag set, bypassing mock wallet');
// Just return success and let the client handle the connection
return NextResponse.json({
success: true,
actionType: 'CONNECT_WALLET',
data: {
needsBrowserConnection: true,
message: 'Client should handle wallet connection directly'
}
});
}
// If mocks are enabled and forceRealWallet is not set, create a mock wallet
if (USE_MOCKS && !action.walletParams?.forceRealWallet) {
console.log('Blockchain API Route: Creating mock wallet service with consistent address');
// Use a consistent mock address for testing
const mockAddress = '0x87a89B578e769F172440581A4E3DE6823dd116bB';
// Create and configure mock wallet service
const mockWalletService = new WalletIntegrationService();
mockWalletService.setMockAddress(mockAddress);
// Store in session manager
sessionManager.storeConnection(effectiveSessionId, mockWalletService, mockAddress);
console.log(`Blockchain API Route: Registered mock wallet ${mockAddress} for session ${effectiveSessionId}`);
console.log('Blockchain API Route: Mock wallet registered successfully');
// Return success with mock address
return NextResponse.json({
success: true,
actionType: 'CONNECT_WALLET',
data: {
address: mockAddress,
provider: action.walletParams?.type
}
});
}
// For server-side regular connections (no mocks, no forceRealWallet)
try {
// Create a mock wallet service for server-side
const walletService = new WalletIntegrationService();
// Use a fixed address for server-side connections to maintain consistency
const serverAddress = '0x87a89B578e769F172440581A4E3DE6823dd116bB' as `0x${string}`;
// Register this connection in the session manager
sessionManager.storeConnection(
effectiveSessionId,
walletService,
serverAddress,
action.walletParams?.chainId || 1
);
console.log(`Blockchain API Route: Registered server-side wallet connection for session ${effectiveSessionId}`);
// Return success response with the server address
return NextResponse.json({
success: true,
actionType: 'CONNECT_WALLET',
data: {
address: serverAddress,
needsBrowserConnection: true
}
});
} catch (error) {
console.error('Blockchain API Route: Error setting up server-side wallet connection:', {
error: error instanceof Error ? error.message : 'Unknown error',
stack: error instanceof Error ? error.stack : 'No stack trace',
sessionId: effectiveSessionId
});
return NextResponse.json({
success: false,
actionType: 'CONNECT_WALLET',
error: 'Failed to set up server-side wallet connection'
});
}
}
// Add session ID to action params if provided
const actionWithSession: BlockchainActionParams = {
...action,
sessionId: effectiveSessionId
};
console.log('Blockchain API Route: Executing action with orchestrator', {
actionType: action.actionType,
sessionId: actionWithSession.sessionId,
originalSessionId: sessionId,
hasTransferParams: !!actionWithSession.transferParams,
hasDeploymentParams: !!actionWithSession.deploymentParams,
activeSessions: Array.from(sessionManager['sessions'].keys())
});
// For other actions, execute them on the server
const result = await blockchainOrchestrator.handleAction(actionWithSession);
console.log('Blockchain API Route: Action completed', {
actionType: action.actionType,
success: result.success,
hasError: !!result.error,
sessionId: actionWithSession.sessionId
});
return NextResponse.json(result);
} catch (error) {
console.error('Blockchain API Route: Error:', {
error: error instanceof Error ? error.message : 'Unknown error',
stack: error instanceof Error ? error.stack : 'No stack trace'
});
return NextResponse.json(
{
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
}
================================================================================
File: app/api/chat/route.ts
================================================================================
import { NextResponse } from 'next/server';
import { AgentOrchestrator } from '@/lib/orchestrator';
const orchestrator = new AgentOrchestrator();
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
const corsHeaders = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};
/**
* Custom JSON serializer that handles BigInt values
* @param key Property key
* @param value Property value
* @returns Serialized value
*/
function bigIntSerializer(key: string, value: any): any {
// Convert BigInt to string
if (typeof value === 'bigint') {
return value.toString();
}
return value;
}
export async function OPTIONS() {
return NextResponse.json({}, { headers: corsHeaders });
}
export async function POST(req: Request) {
console.log('Chat API: Starting request processing');
console.log('Headers:', Object.fromEntries(req.headers.entries()));
try {
let body;
try {
const text = await req.text();
console.log('Raw request body:', text);
body = JSON.parse(text);
console.log('Chat API: Request body parsed:', body);
} catch (error) {
console.error('Chat API: JSON parsing error:', error);
return NextResponse.json(
{ error: 'Invalid JSON in request body' },
{ status: 400, headers: corsHeaders }
);
}
const { query, sessionId } = body;
console.log('Chat API: Extracted sessionId:', sessionId);
console.log('Chat API: Extracted query:', query);
if (!query?.trim()) {
console.log('Chat API: Empty query received');
return NextResponse.json(
{ error: 'Query is required' },
{ status: 400, headers: corsHeaders }
);
}
if (!sessionId?.trim()) {
console.log('Chat API: No sessionId received');
return NextResponse.json(
{
error: 'Session ID is required',
debug: {
body,
headers: Object.fromEntries(req.headers.entries())
}
},
{ status: 400, headers: corsHeaders }
);
}
console.log('Chat API: Starting chat pipeline for query:', query);
console.log('Chat API: Using session ID:', sessionId);
const result = await orchestrator.processQuery(query, sessionId);
console.log('Chat API: Pipeline complete. Analysis:', result.analysis.classification.primaryIntent);
console.log('Chat API: Generated response:', result.response);
// Use the custom serializer to handle BigInt values
const responseData = {
response: result.response,
data: result.aggregatorData,
analysis: result.analysis,
suggestions: result.suggestions,
contextAnalysis: result.contextAnalysis
};
// Create a serialized version of the response data
const serializedData = JSON.stringify(responseData, bigIntSerializer);
// Return the response with the serialized data
return new NextResponse(serializedData, {
status: 200,
headers: {
...corsHeaders,
'Content-Type': 'application/json'
}
});
} catch (error) {
console.error('Chat API error:', error);
let errorMessage = 'Failed to process chat request';
let statusCode = 500;
if (error instanceof Error) {
if (error.message.includes('API key')) {
errorMessage = 'Service configuration error';
statusCode = 503;
} else if (error.message.includes('rate limit')) {
errorMessage = 'Service is busy, please try again in a moment';
statusCode = 429;
} else if (error.message.includes('validation')) {
errorMessage = error.message;
statusCode = 400;
} else if (error.message.includes('Session ID is required')) {
errorMessage = 'Session ID is required';
statusCode = 400;
} else {
errorMessage = error.message;
}
}
// Use the custom serializer for error responses as well
const errorData = {
error: errorMessage,
status: statusCode
};
const serializedError = JSON.stringify(errorData, bigIntSerializer);
return new NextResponse(serializedError, {
status: statusCode,
headers: {
...corsHeaders,
'Content-Type': 'application/json'
}
});
}
}
================================================================================
File: app/api/token-data/route.ts
================================================================================
import { NextResponse } from 'next/server';
import { getTrendingTokens, getTokenPrices } from '@/lib/token-data';
import { withRateLimit } from '@/lib/rate-limit';
import { withAuth } from '@/lib/middleware';
const handler = withAuth(
withRateLimit(async (req: Request) => {
try {
const trendingTokens = await getTrendingTokens();
const tokenIds = trendingTokens.map(trend => trend.item.id);
const tokenPrices = await getTokenPrices(tokenIds);
const enrichedTrends = trendingTokens.map(trend => ({
...trend,
price_data: tokenPrices[trend.item.id] || null,
}));
return NextResponse.json({ data: enrichedTrends });
} catch (error) {
console.error('Token data error:', error);
return NextResponse.json(
{ error: 'Failed to fetch token data' },
{ status: 500 }
);
}
})
);
export { handler as GET };
================================================================================
File: app/blockchain-test/page.tsx
================================================================================
"use client";
import React, { useState, useEffect, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Separator } from '@/components/ui/separator';
import { Loader2, Wallet, Send, FileCode, Blocks, AlertCircle, History } from 'lucide-react';
import { WalletConnect } from '@/components/WalletConnect';
import { blockchainApi } from '@/lib/api/blockchain-api';
import { USE_MOCKS, USE_HARDHAT, USE_TESTNET, DEFAULT_NETWORK } from '@/lib/blockchain/config';
import { TransferResult } from '@/lib/agents/transaction/token-transfer-agent';
import { transactionApi, TransactionRecord } from '@/lib/api/transaction-api';
import { TokenTransferAgent } from '@/lib/agents/transaction/token-transfer-agent';
import { ContractDeploymentAgent } from '@/lib/agents/deployment/contract-deployment-agent';
export default function BlockchainTestPage() {
const [activeTab, setActiveTab] = useState('wallet');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const [environment, setEnvironment] = useState('');
const [sessionId, setSessionId] = useState<string | null>(null);
const [walletAddress, setWalletAddress] = useState<string | null>(null);
// Transaction history
const [transactions, setTransactions] = useState<TransactionRecord[]>([]);
// Transfer state
const [recipient, setRecipient] = useState('');
const [amount, setAmount] = useState('');
const [tokenAddress, setTokenAddress] = useState('');
const [txHash, setTxHash] = useState('');
// Contract deployment state
const [templates, setTemplates] = useState<any[]>([]);
const [selectedTemplate, setSelectedTemplate] = useState('erc20-token');
const [tokenName, setTokenName] = useState('Test Token');
const [tokenSymbol, setTokenSymbol] = useState('TEST');
const [tokenDecimals, setTokenDecimals] = useState('18');
const [tokenSupply, setTokenSupply] = useState('1000000');
// Memoize event handlers to prevent unnecessary re-renders
const handleTransactionAdded = useCallback((transaction: TransactionRecord) => {
console.log('🔵 Blockchain test page received transaction:added event:', transaction);
setTransactions(prev => {
// Check if transaction already exists
const exists = prev.some(t => t.transactionHash === transaction.transactionHash);
if (exists) {
console.log('🔵 Transaction already exists, updating:', transaction.transactionHash);
return prev.map(t =>
t.transactionHash === transaction.transactionHash ? transaction : t
);
} else {
console.log('🔵 Adding new transaction:', transaction.transactionHash);
return [transaction, ...prev];
}
});
}, []);
const handleTransactionUpdated = useCallback((transaction: TransactionRecord) => {
console.log('🟢 Blockchain test page received transaction:updated event:', transaction);
setTransactions(prev => {
// Check if transaction exists
const exists = prev.some(t => t.transactionHash === transaction.transactionHash);
if (exists) {
console.log('🟢 Updating existing transaction:', transaction.transactionHash);
return prev.map(t =>
t.transactionHash === transaction.transactionHash ? transaction : t
);
} else {
console.log('🟢 Transaction not found in state, adding:', transaction.transactionHash);
return [transaction, ...prev];
}
});
}, []);
// Add a separate effect for transaction monitoring
useEffect(() => {
console.log('DEBUG - Setting up transaction event listeners');
// Register event handlers
transactionApi.subscribe('transaction:added', handleTransactionAdded);
transactionApi.subscribe('transaction:updated', handleTransactionUpdated);
// Initial load of transactions
console.log('DEBUG - Loading initial transactions');
loadTransactionHistory();
// Return cleanup function
return () => {
console.log('DEBUG - Cleaning up transaction event listeners');
transactionApi.unsubscribe('transaction:added', handleTransactionAdded);
transactionApi.unsubscribe('transaction:updated', handleTransactionUpdated);
};
}, [handleTransactionAdded, handleTransactionUpdated]);
// Add periodic debugging
useEffect(() => {
console.log('DEBUG - Setting up transaction debug interval');
const logTransactions = () => {
console.log('🔍 TRANSACTION DEBUG:');
console.log('- API transactions:', transactionApi.getAllTransactions());
console.log('- Component state:', transactions);
console.log('- TokenTransferAgent transfers:',
TokenTransferAgent.getAllTransfers().length);
console.log('- ContractDeploymentAgent deployments:',
ContractDeploymentAgent.getAllDeployments().length);
};
// Log immediately and then every 10 seconds
logTransactions();
const interval = setInterval(logTransactions, 10000);
return () => {
console.log('DEBUG - Cleaning up transaction debug interval');
clearInterval(interval);
};
}, [transactions]);
useEffect(() => {
// Determine environment
let envType = 'Unknown';
if (USE_MOCKS) envType = 'Mock Implementation';
else if (USE_HARDHAT) envType = 'Local Hardhat Network';
else if (USE_TESTNET) envType = 'Public Testnet (Sepolia)';
else envType = 'Mainnet';
setEnvironment(`${envType} (${DEFAULT_NETWORK})`);
// Set session ID to default-session for consistency with chat interface
const defaultSessionId = 'default-session';
setSessionId(defaultSessionId);
console.log('Setting fixed session ID:', defaultSessionId);
// Set the session ID in the blockchain API
blockchainApi.setSessionId(defaultSessionId);
console.log('Session ID set in blockchain API:', defaultSessionId);
// Load contract templates
loadTemplates();
// Load transaction history from local storage
loadTransactionHistory();
}, []); // Empty dependency array so this only runs once on mount
// Generate a unique session ID
const generateSessionId = (): string => {
// Always use "default-session" to match the chat interface
console.log('Using default-session for consistency with chat interface');
return 'default-session';
};
// Load transaction history from local storage
const loadTransactionHistory = () => {
try {
console.log('Loading transactions from transaction API');
const transactions = transactionApi.getAllTransactions();
console.log(`Loaded ${transactions.length} transactions`);
setTransactions(transactions);
} catch (error) {
console.error('Error loading transaction history:', error);
setError(`Failed to load transaction history: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
};
// Add a transaction to history
const addTransaction = (hash: string, type: 'transfer' | 'deploy', details: any) => {
try {
console.log(`Adding transaction ${hash} to local state`);
// Just add to local state for UI, the global registry already has it
const newTransaction: TransactionRecord = {
transactionHash: hash as `0x${string}`,
status: 'pending',
timestamp: Date.now(),
type,
...(type === 'transfer'
? {
tokenAddress: details.tokenAddress,
to: details.to,
amount: details.amount
}
: {
templateId: details.templateId,
contractAddress: null
}
)
};
setTransactions(prev => {
const updated = [newTransaction, ...prev.filter(t => t.transactionHash !== hash)];
return updated;
});
} catch (error) {
console.error('Error adding transaction:', error);
}
};
// Update a transaction in history
const updateTransaction = (hash: string, status: string, details: any) => {
try {
console.log(`Updating transaction ${hash} status to ${status}`);
// Get the latest transaction data from our API
const latestTransaction = transactionApi.getTransaction(hash as `0x${string}`);
if (!latestTransaction) {
console.warn(`Transaction ${hash} not found in global registry`);
return;
}
// Update the local state for UI
setTransactions(prev => {
const updated = [...prev];
const index = updated.findIndex(t => t.transactionHash === hash);
if (index !== -1) {
updated[index] = {
...updated[index],
...latestTransaction
};
}
return updated;
});
} catch (error) {
console.error('Error updating transaction:', error);
}
};
const loadTemplates = async () => {
try {
blockchainApi.setSessionId(sessionId!);
const availableTemplates = await blockchainApi.getContractTemplates();
console.log('Available templates:', availableTemplates);
setTemplates(availableTemplates);
// If no template is selected and we have templates, select the first one
if (!selectedTemplate && availableTemplates.length > 0) {
setSelectedTemplate('erc20-token'); // Default to ERC20 token template
console.log('Selected default template: erc20-token');
}
} catch (error) {
console.error('Failed to load templates:', error);
}
};
const handleConnectWallet = async () => {
try {
console.log('Connecting wallet with session ID:', sessionId);
// Connect wallet using the blockchain API
const address = await blockchainApi.connectWallet('metamask');
console.log('Wallet connected successfully:', address);
// Update wallet address state
setWalletAddress(address);
// Show success message
setSuccess(`Wallet connected: ${address}`);
setError(null);
} catch (err: any) {
console.error('Wallet connection failed:', err);
setError(`Failed to connect wallet: ${err.message}`);
setSuccess(null);
}
};
const WalletConnectionSection = () => (
<div className="mb-6 space-y-4">
<div className="flex flex-col space-y-2">
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-medium">Session Information</h3>
<p className="text-sm text-muted-foreground">
Session ID: {sessionId || 'Not set'}
</p>
{walletAddress && (
<p className="text-sm text-muted-foreground">
Wallet: {`${walletAddress.slice(0, 6)}...${walletAddress.slice(-4)}`}
</p>
)}
</div>
<Button
onClick={handleConnectWallet}
variant="outline"
className="flex items-center space-x-2"
>
<Wallet className="h-4 w-4" />
<span>Connect Wallet</span>
</Button>
</div>
</div>
<WalletConnect onConnect={(address) => {
console.log('Wallet connected via WalletConnect:', address);
setWalletAddress(address);
}} />
</div>
);
const handleTransfer = async () => {
setLoading(true);
setError(null);
setSuccess(null);
console.log('Initiating token transfer:', {
recipient,
amount,
tokenAddress: tokenAddress || 'ETH (native)',
sessionId,
walletAddress
});
try {
// Check if wallet is connected
if (!walletAddress) {
console.error('Wallet not connected');
setError('Wallet not connected. Please connect your wallet first.');
setLoading(false);
return;
}
// Verify session ID is set in the API
console.log('Verifying session ID in blockchain API:', blockchainApi.getSessionId());
if (blockchainApi.getSessionId() !== sessionId) {
console.warn('Session ID mismatch, updating in API:', {
current: blockchainApi.getSessionId(),
expected: sessionId
});
blockchainApi.setSessionId(sessionId!);
}
const result = await blockchainApi.transferTokens(
recipient,
amount,
tokenAddress || undefined
);
console.log('Transfer result:', result);
setTxHash(result.transactionHash);
setSuccess(`Transaction submitted: ${result.transactionHash}`);
// Add to transaction history
addTransaction(result.transactionHash, 'transfer', {
recipient,
amount,
tokenAddress: tokenAddress || 'ETH',
status: result.status
});
} catch (err: any) {
console.error('Transfer failed:', err);
setError(err.message || 'Transfer failed');
} finally {
setLoading(false);
}
};
const handleDeploy = async () => {
setLoading(true);
setError(null);
setSuccess(null);
console.log('Initiating contract deployment:', {
template: 'erc20-token', // Force correct template ID
params: {
name: tokenName,
symbol: tokenSymbol,
decimals: parseInt(tokenDecimals, 10),
initialSupply: tokenSupply
},
sessionId,
walletAddress
});
try {
// Check if wallet is connected
if (!walletAddress) {
console.error('Wallet not connected');
setError('Wallet not connected. Please connect your wallet first.');
setLoading(false);
return;
}
// Verify session ID is set in the API
console.log('Verifying session ID in blockchain API:', blockchainApi.getSessionId());
if (blockchainApi.getSessionId() !== sessionId) {
console.warn('Session ID mismatch, updating in API:', {
current: blockchainApi.getSessionId(),
expected: sessionId
});
blockchainApi.setSessionId(sessionId!);
}
// For ERC20 token template, provide parameters
const params = {
templateParams: {
name: tokenName // This is for replacing {{name}} in the template
},
constructorArgs: [
tokenName, // _name parameter
tokenSymbol, // _symbol parameter
tokenSupply, // _initialSupply parameter
walletAddress // _owner parameter
]
};
console.log('Deployment parameters:', params);
const result = await blockchainApi.deployContract(
'erc20-token', // Force correct template ID
params
);
console.log('Deployment result:', result);
setTxHash(result.transactionHash);
setSuccess(`Contract deployed: ${result.contractAddress}`);
// Add to transaction history
addTransaction(result.transactionHash, 'deploy', {
template: 'erc20-token',
contractAddress: result.contractAddress,
params,
status: 'pending'
});
} catch (err: any) {
console.error('Deployment failed:', err);
setError(err.message || 'Deployment failed');
} finally {
setLoading(false);
}
};
const handleRefreshStatus = async () => {
if (!txHash) return;
setLoading(true);
console.log('Refreshing transaction status for:', txHash);
try {
if (activeTab === 'transfer') {
const status = await blockchainApi.getTransferStatus(txHash);
console.log('Transfer status:', status);
setSuccess(`Status: ${status.status}, Confirmations: ${status.confirmations || 0}`);
// Update transaction in history
updateTransaction(txHash, status.status, status);
} else {
const status = await blockchainApi.getDeploymentStatus(txHash);
console.log('Deployment status:', status);
// Extract status and confirmations with fallbacks
const deployStatus = status.deploymentStatus || (status.contractAddress ? 'success' : 'pending');
const confirmations = status.confirmations || 0;
setSuccess(`Status: ${deployStatus}, Contract: ${status.contractAddress}, Confirmations: ${confirmations}`);
// Update transaction in history
updateTransaction(txHash, deployStatus, status);
}
} catch (err: any) {
console.error('Error checking status:', err);
setError(err.message || 'Failed to check status');
} finally {
setLoading(false);
}
};
// Clear transaction history
const clearTransactionHistory = () => {
setTransactions([]);
console.log('Transaction history cleared');
};
return (
<div className="container mx-auto py-10">
<Card>
<CardHeader>
<CardTitle>Blockchain Testing Interface</CardTitle>
<CardDescription>
Test blockchain functionality in isolation
</CardDescription>
<div className="bg-muted p-2 rounded-md text-sm mt-2">
<strong>Environment:</strong> {environment}
</div>
</CardHeader>
<CardContent>
<WalletConnectionSection />
<Tabs defaultValue="wallet" value={activeTab} onValueChange={setActiveTab}>
<TabsList className="grid grid-cols-4 mb-6">
<TabsTrigger value="wallet">
<Wallet className="h-4 w-4 mr-2" />
Wallet
</TabsTrigger>
<TabsTrigger value="transfer">
<Send className="h-4 w-4 mr-2" />
Transfer
</TabsTrigger>
<TabsTrigger value="deploy">
<FileCode className="h-4 w-4 mr-2" />
Deploy Contract
</TabsTrigger>
<TabsTrigger value="history">
<History className="h-4 w-4 mr-2" />
History
</TabsTrigger>
</TabsList>
<TabsContent value="wallet">
<Card>
<CardHeader>
<CardTitle>Wallet Information</CardTitle>
</CardHeader>