-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
2421 lines (2136 loc) · 85.2 KB
/
main.js
File metadata and controls
2421 lines (2136 loc) · 85.2 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
const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron');
const { autoUpdater } = require('electron-updater');
const path = require('path');
const { spawn, execSync, fork } = require('child_process');
const fs = require('fs');
const { WalletEncryption } = require('./src/utils/walletEncryption.cjs');
const { registerTokenHandlers } = require('./token-handlers');
// Import the botLauncher module with fallback
let botLauncher;
try {
botLauncher = require('./src/botLauncher.cjs');
console.log('✅ botLauncher module loaded successfully');
} catch (error) {
console.error('❌ Failed to load botLauncher module:', error.message);
// Fallback to null - we'll use npm scripts instead
botLauncher = null;
}
// 🎯 CENTRALIZED TRUSTBOT CLEANUP FUNCTION
// Final step to kill lingering TRUSTBOT.exe processes across all exit paths
function performFinalTrustbotCleanup() {
if (process.platform === 'win32') {
try {
const ourPid = process.pid;
console.log('🎯 [FINAL-CLEANUP] Performing final TRUSTBOT.exe cleanup...');
execSync(`taskkill /f /im TRUSTBOT.exe /fi "PID ne ${ourPid}"`, { stdio: 'ignore' });
console.log('✅ [FINAL-CLEANUP] All other TRUSTBOT processes terminated');
} catch (error) {
console.log('ℹ️ [FINAL-CLEANUP] No other TRUSTBOT processes found to clean up');
}
}
}
// JSON Database for wallets and config
// Consistent path logic for both dev and packaged apps
// Use userData directory for persistent storage across updates
function getWalletsPath() {
if (app.isPackaged) {
return path.join(app.getPath('userData'), 'wallets.json');
} else {
return path.join(__dirname, 'wallets.json');
}
}
function getConfigPath() {
if (app.isPackaged) {
return path.join(app.getPath('userData'), 'config.json');
} else {
return path.join(__dirname, 'config.json');
}
}
const WALLETS_DB_PATH = getWalletsPath();
const CONFIG_PATH = getConfigPath();
// Set environment variable so UI gas price service can find wallets.json
process.env.WALLETS_DB_PATH = WALLETS_DB_PATH;
// Global process tracking for cleanup
let childProcesses = [];
// Export childProcesses for access from other modules
module.exports = { childProcesses };
// Initialize wallets database
function initializeWalletsDB() {
if (!fs.existsSync(WALLETS_DB_PATH)) {
// Try to copy from wallets.example.json first
const walletsExamplePath = app.isPackaged
? path.join(process.resourcesPath, 'app.asar.unpacked', 'wallets.example.json')
: path.join(__dirname, 'wallets.example.json');
if (fs.existsSync(walletsExamplePath)) {
try {
fs.copyFileSync(walletsExamplePath, WALLETS_DB_PATH);
console.log('✅ Created wallets.json from wallets.example.json');
return;
} catch (error) {
console.warn('⚠️ Failed to copy wallets.example.json, creating default:', error.message);
}
}
// Fallback to creating default data programmatically
const defaultData = {
config: {
rpcUrl: "https://base-rpc.publicnode.com",
chainId: 8453,
virtualTokenAddress: "0x0b3e328455c4059EEb9e3f84b5543F74E24e7E1b"
},
wallets: []
};
fs.writeFileSync(WALLETS_DB_PATH, JSON.stringify(defaultData, null, 2));
console.log('✅ Created wallets.json with default data');
}
}
// Read wallets database
function readWalletsDB() {
try {
const data = fs.readFileSync(WALLETS_DB_PATH, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error('Error reading wallets database:', error);
return null;
}
}
// Write wallets database
function writeWalletsDB(data) {
try {
// Before writing, ensure we preserve the existing config section
let existingData = {};
try {
if (fs.existsSync(WALLETS_DB_PATH)) {
const existingContent = fs.readFileSync(WALLETS_DB_PATH, 'utf8');
existingData = JSON.parse(existingContent);
}
} catch (readError) {
console.warn('Could not read existing wallets.json, proceeding with new data');
}
// Merge configs properly - preserve dynamicRpcs if not provided in new data
const mergedConfig = { ...existingData.config, ...data.config };
if (!data.config?.dynamicRpcs && existingData.config?.dynamicRpcs) {
mergedConfig.dynamicRpcs = existingData.config.dynamicRpcs;
}
const finalData = {
...data,
config: mergedConfig
};
fs.writeFileSync(WALLETS_DB_PATH, JSON.stringify(finalData, null, 2));
return true;
} catch (error) {
console.error('Error writing wallets database:', error);
return false;
}
}
// Validate private key and get address using ethers.js
function getAddressFromPrivateKey(privateKey, encryptedKey = null) {
try {
// If encrypted key is provided and plaintext key is empty, try to decrypt
if (encryptedKey && (!privateKey || privateKey === '')) {
try {
console.log('Attempting to decrypt private key from encrypted data');
// Use the master password for decryption if available
const masterPassword = global.masterPassword;
if (!masterPassword) {
console.error('No master password available for decryption');
return null;
}
privateKey = WalletEncryption.decryptPrivateKey(encryptedKey, masterPassword);
if (!privateKey) {
console.error('Failed to decrypt private key');
return null;
}
} catch (decryptError) {
console.error('Error decrypting private key:', decryptError);
return null;
}
}
// Ensure private key is properly formatted
if (!privateKey) {
console.error('No private key provided');
return null;
}
// Add 0x prefix if not present for ethers.js
if (!privateKey.startsWith('0x')) {
privateKey = '0x' + privateKey;
}
// Validate private key length (64 hex chars + 0x prefix = 66 total)
if (privateKey.length !== 66) {
console.error('Invalid private key length:', privateKey.length);
return null;
}
// Use ethers.js to validate and get address
const ethers = require('ethers');
const wallet = new ethers.Wallet(privateKey);
console.log('✅ Private key validated successfully');
return wallet.address;
} catch (error) {
console.error('Error validating private key:', error.message);
return null;
}
}
// IPC handler for validating private keys securely in the main process
ipcMain.handle('validate-private-key', async (event, privateKey, encryptedKey) => {
try {
console.log('Validating private key in main process');
const address = getAddressFromPrivateKey(privateKey, encryptedKey);
if (!address) {
throw new Error('Invalid private key format');
}
return address;
} catch (error) {
console.error('Error validating private key:', error);
throw new Error('Invalid private key: ' + error.message);
}
});
// Provide userData path to renderer for reading updated token files
ipcMain.handle('get-user-data-path', async () => {
try {
return app.getPath('userData');
} catch (e) {
return null;
}
});
// Allow renderer to trigger token ticker update on demand
ipcMain.handle('run-ticker-update', async () => {
try {
// If an update is already in progress, return immediately
if (runAutomaticTickerUpdate.inProgress) {
return { success: true, inProgress: true, message: 'Update already in progress' };
}
// Start update in background and return immediately
Promise.resolve()
.then(() => runAutomaticTickerUpdate())
.catch(err => {
console.error('Background ticker update failed:', err);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('ticker-update-completed', {
success: false,
message: 'Failed to update token database',
error: err?.message || String(err)
});
}
});
return { success: true, inProgress: true };
} catch (e) {
console.error('run-ticker-update failed:', e);
return { success: false, error: e?.message || String(e) };
}
});
// Global variable to track console window
let consoleWindow = null;
// IPC handler for creating console window
ipcMain.handle('create-console-window', async (event) => {
try {
// If window already exists, focus it
if (consoleWindow && !consoleWindow.isDestroyed()) {
consoleWindow.focus();
return { success: true, windowId: consoleWindow.id };
}
// Create new console window
consoleWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 800,
minHeight: 600,
autoHideMenuBar: true,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true
},
icon: path.join(__dirname, 'assets', 'icon.ico'), // Application icon
title: 'TRUSTBOT - Detailed Console',
show: false,
frame: true,
titleBarStyle: 'default',
parent: mainWindow, // Make it a child of main window
modal: false // Allow interaction with main window
});
// Load console HTML content
const consoleHtml = `
<!DOCTYPE html>
<html>
<head>
<title>TRUSTBOT - Detailed Console</title>
<style>
body {
margin: 0;
padding: 20px;
background: #0d1117;
color: #f0f6fc;
font-family: 'Courier New', monospace;
font-size: 13px;
line-height: 1.4;
overflow-x: hidden;
}
.console-header {
position: sticky;
top: 0;
background: #0d1117;
padding: 0 0 20px 0;
border-bottom: 2px solid #30363d;
margin-bottom: 20px;
z-index: 1000;
}
.console-content {
min-height: calc(100vh - 100px);
}
.console-line {
margin: 2px 0;
padding: 2px 0;
word-wrap: break-word;
white-space: pre-wrap;
}
.console-line.stderr {
color: #ff6b6b;
}
.console-line.stdout {
color: #f0f6fc;
}
.console-timestamp {
color: #7d8590;
font-size: 11px;
}
button {
background: #21262d;
border: 1px solid #30363d;
color: #f0f6fc;
padding: 4px 8px;
border-radius: 4px;
cursor: pointer;
margin-right: 6px;
font-size: 11px;
font-weight: 500;
transition: all 0.2s ease;
white-space: nowrap;
}
button:hover {
background: #30363d;
border-color: #484f58;
transform: translateY(-1px);
}
.clear-btn {
background: #da3633 !important;
border-color: #f85149 !important;
}
.clear-btn:hover {
background: #f85149 !important;
border-color: #ff7b72 !important;
}
/* Transaction enhancement styles */
.tx-hash {
color: #58a6ff !important;
font-weight: bold;
background: rgba(88, 166, 255, 0.1);
padding: 1px 3px;
border-radius: 3px;
}
.tx-amount {
color: #a5a5ff !important;
font-weight: bold;
background: rgba(165, 165, 255, 0.1);
padding: 1px 3px;
border-radius: 3px;
}
.tx-status-success {
color: #3fb950 !important;
font-weight: bold;
}
.tx-status-pending {
color: #d29922 !important;
font-weight: bold;
}
.tx-status-failed {
color: #f85149 !important;
font-weight: bold;
}
</style>
</head>
<body>
<div class="console-header">
<div style="display: flex; justify-content: space-between; align-items: center;">
<h2 style="margin: 0; color: #58a6ff; font-size: 18px; font-weight: bold;">📊 TRUSTBOT - Detailed Console</h2>
<div>
<button onclick="clearConsole()">🗑️ Clear</button>
<button onclick="scrollToBottom()">⬇️ Scroll to Bottom</button>
<button class="clear-btn" onclick="window.close()">❌ Close Window</button>
</div>
</div>
</div>
<div class="console-content" id="console-window">
<div class="console-line" style="color: #7d8590; font-style: italic;">
[${new Date().toLocaleTimeString()}] Console window opened - waiting for messages...
</div>
</div>
<script>
const { ipcRenderer } = require('electron');
function clearConsole() {
const console = document.getElementById('console-window');
console.innerHTML = '<div class="console-line" style="color: #7d8590; font-style: italic;">[' + new Date().toLocaleTimeString() + '] Console cleared</div>';
// Send IPC message to main process to clear the normal console
ipcRenderer.invoke('clear-console-from-detailed').catch(error => {
console.error('Error clearing main console:', error);
});
}
function scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
// Listen for console messages from main process
ipcRenderer.on('console-message', (event, data) => {
const { message, type } = data;
addMessage(message, type);
});
function addMessage(message, type = 'stdout') {
const consoleEl = document.getElementById('console-window');
const timestamp = new Date().toLocaleTimeString();
const line = document.createElement('div');
line.className = \`console-line \${type}\`;
// Clean message
const cleanMessage = message
.replace(/[^\\w\\s\\.\\-\\:\\(\\)\\[\\]\\/\\\\%]/g, '')
.replace(/\\b(amazing|awesome|great|excellent|fantastic|perfect|wow|cool|exciting|incredible)\\b/gi, '')
.replace(/\\s+/g, ' ')
.trim();
line.innerHTML = \`<span class="console-timestamp">[\${timestamp}]</span> \${cleanMessage}\`;
// Apply transaction enhancement
enhanceMessage(line);
consoleEl.appendChild(line);
// Auto-scroll
window.scrollTo(0, document.body.scrollHeight);
}
function enhanceMessage(lineElement) {
let content = lineElement.innerHTML;
// Enhance transaction hashes
content = content.replace(/(0x[a-fA-F0-9]{40,})/g, '<span class="tx-hash">$1</span>');
// Enhance amounts
content = content.replace(/(\\d+\\.\\d+)\\s*(ETH|VIRTUAL|TRUST|BRO|USDC|USDT)/g, '<span class="tx-amount">$1 $2</span>');
// Enhance status indicators
content = content.replace(/\\b(Success|SUCCESSFUL|Confirmed|CONFIRMED)\\b/g, '<span class="tx-status-success">$1</span>');
content = content.replace(/\\b(Pending|PENDING|Processing)\\b/g, '<span class="tx-status-pending">$1</span>');
content = content.replace(/\\b(Failed|FAILED|Error|ERROR)\\b/g, '<span class="tx-status-failed">$1</span>');
lineElement.innerHTML = content;
}
// Auto-scroll observer
const observer = new MutationObserver(() => {
window.scrollTo(0, document.body.scrollHeight);
});
observer.observe(document.getElementById('console-window'), { childList: true });
</script>
</body>
</html>
`;
consoleWindow.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(consoleHtml));
// Show window when ready
consoleWindow.once('ready-to-show', () => {
consoleWindow.show();
consoleWindow.focus();
// Notify renderer process that console window is ready to receive messages
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('console-window-ready');
}
});
// Clean up reference when window is closed
consoleWindow.on('closed', () => {
consoleWindow = null;
// Notify renderer process that console window was closed
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('console-window-closed');
}
});
return { success: true, windowId: consoleWindow.id };
} catch (error) {
console.error('Error creating console window:', error);
throw error;
}
})
// IPC handler for sending messages to console window
ipcMain.handle('send-console-message', async (event, message, type = 'stdout') => {
try {
if (consoleWindow && !consoleWindow.isDestroyed()) {
consoleWindow.webContents.send('console-message', { message, type });
return { success: true };
}
return { success: false, error: 'Console window not open' };
} catch (error) {
console.error('Error sending console message:', error);
throw error;
}
})
// IPC handler for clearing console from detailed window
ipcMain.handle('clear-console-from-detailed', async (event) => {
try {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('clear-console-request');
return { success: true };
}
return { success: false, error: 'Main window not available' };
} catch (error) {
console.error('Error clearing console from detailed window:', error);
throw error;
}
})
// Map bot types to npm scripts for the new autotrade structure
function getNpmScriptForBot(botType) {
const scriptMap = {
'buybot': 'buybot',
'sellbot': 'sellbot',
'sellbot-fsh': 'sellbot', // FSH will be handled via arguments
'farmbot': 'farmbot',
'jeetbot': 'jeetbot',
// Advanced Bot (formerly sniper): npm script is named 'sniperbot'
'snipebot': 'sniperbot',
'mmbot': 'mmbot',
'transferbot': 'transferbot',
'stargate': 'stargate',
'contactbot': 'contactbot',
'detect': 'detect',
'detect-quick': 'detect:quick',
'ticker-search': 'ticker:search',
'ticker-fetch': 'ticker:fetch',
'ticker-export': 'ticker:export',
'ticker-new': 'ticker:new',
'ticker-update': 'ticker:update',
'ticker-runall': 'ticker',
'sell-all': 'sellbot' // sell-all will use sellbot with fsh argument
};
return scriptMap[botType] || botType;
}
// Keep a global reference of the window object
let mainWindow;
function createWindow() {
// Create the browser window
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 1200,
minHeight: 800,
autoHideMenuBar: true, // Hide menu bar for clean UI
webPreferences: {
nodeIntegration: true,
contextIsolation: false, // Keep false for compatibility with existing code
enableRemoteModule: true
},
icon: path.join(__dirname, 'assets', 'icon.ico'), // Application icon
title: 'VIRTUAL Trading Bot Desktop',
show: false,
frame: true,
titleBarStyle: 'default'
});
// Load the index.html
mainWindow.loadFile('index.html');
// Show window when ready
mainWindow.once('ready-to-show', () => {
mainWindow.show();
// Make main window globally accessible for the auto-updater
global.mainWindow = mainWindow;
// Check for and clear any update flags from previous update attempts
try {
const updateFlagPath = path.join(app.getPath('userData'), 'update-in-progress');
if (fs.existsSync(updateFlagPath)) {
console.log('💾 Found update flag file, this appears to be a restart after update');
// Delete the flag file
fs.unlinkSync(updateFlagPath);
console.log('💾 Cleared update flag file');
// Set a flag to indicate this is a fresh restart after update
// This will prevent showing update notifications immediately after update
const recentUpdateFlagPath = path.join(app.getPath('userData'), 'recent-update');
fs.writeFileSync(recentUpdateFlagPath, new Date().toISOString());
console.log('💾 Created recent update flag to prevent immediate update checks');
}
} catch (err) {
console.error('❌ Error checking update flag:', err);
}
// Initialize auto-updater now that window is ready
try {
const { initAutoUpdater } = require('./src/auto-updater.cjs');
console.log('🔄 Initializing auto-updater from main.js...');
initAutoUpdater(mainWindow);
// Add keyboard shortcut for manual update check (Cmd+U on Mac, Ctrl+U on others)
const { globalShortcut } = require('electron');
const shortcut = process.platform === 'darwin' ? 'CommandOrControl+U' : 'Ctrl+U';
globalShortcut.register(shortcut, () => {
console.log('🔄 Manual update check triggered via keyboard shortcut');
mainWindow.webContents.send('trigger-manual-update-check');
});
console.log(`🔄 Registered ${shortcut} for manual update check`);
} catch (error) {
console.error('❌ Failed to initialize auto-updater:', error);
}
// Focus the window
if (process.platform === 'darwin') {
app.dock.show();
}
mainWindow.focus();
// Kick off automatic token ticker update on app startup (always enabled)
try {
console.log('🚀 Triggering automatic token update on startup...');
runAutomaticTickerUpdate().catch(err => {
console.error('❌ Automatic token update failed:', err);
});
} catch (e) {
console.error('❌ Failed to start automatic token update:', e);
}
});
// Open external links in browser
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
// Handle window closed - COMPREHENSIVE CLEANUP from trace documentation
mainWindow.on('closed', () => {
console.log('🔍 [MAIN.JS] Main window closed - comprehensive cleanup sequence...');
try {
const { execSync } = require('child_process');
const ourPid = process.pid;
// 🎯 CRITICAL FIX: Close placeholder window from secureBootstrap.js
// This is the root cause of lingering processes in EXE build
try {
// Access the placeholder window from global scope or require secureBootstrap
if (global.placeholderWindow && !global.placeholderWindow.isDestroyed()) {
console.log('🔧 [MAIN.JS] Closing placeholder window from secureBootstrap.js...');
global.placeholderWindow.close();
global.placeholderWindow = null;
console.log('✅ [MAIN.JS] Placeholder window closed successfully');
} else {
console.log('ℹ️ [MAIN.JS] No placeholder window found or already destroyed');
}
} catch (error) {
console.log('⚠️ [MAIN.JS] Error closing placeholder window:', error.message);
}
// Close console window if open
if (consoleWindow && !consoleWindow.isDestroyed()) {
console.log('🔧 [MAIN.JS] Closing console window...');
consoleWindow.close();
consoleWindow = null;
console.log('✅ [MAIN.JS] Console window closed successfully');
} else {
console.log('ℹ️ [MAIN.JS] No console window to close');
}
// Kill tracked child processes
console.log(`🔧 [MAIN.JS] Cleaning up ${childProcesses.length} tracked child processes...`);
childProcesses.forEach(process => {
try {
if (!process.killed) {
if (process.platform === 'win32') {
try {
execSync(`taskkill /pid ${process.pid} /t /f`, { stdio: 'ignore' });
console.log(`✅ [MAIN.JS] Killed child process tree: ${process.pid}`);
} catch (error) {
console.log(`ℹ️ [MAIN.JS] Process ${process.pid} already terminated`);
}
} else {
process.kill('SIGTERM');
setTimeout(() => {
if (!process.killed) {
process.kill('SIGKILL');
}
}, 1000);
}
}
} catch (error) {
console.log(`ℹ️ [MAIN.JS] Error killing process ${process.pid}:`, error.message);
}
});
// Clear the array
childProcesses.length = 0;
console.log('✅ [MAIN.JS] Child processes array cleared');
// Kill any lingering processes
if (process.platform === 'win32') {
// 🎯 CRITICAL: Kill other TRUSTBOT.exe processes to prevent background lingering
// This prevents the 3 background TRUSTBOT processes shown in Task Manager
// Excludes current PID to avoid self-termination, safe for update installer
try {
console.log('🔧 [MAIN.JS] Killing other TRUSTBOT.exe processes...');
execSync(`taskkill /f /im TRUSTBOT.exe /fi "PID ne ${ourPid}"`, { stdio: 'ignore' });
console.log('✅ [MAIN.JS] Cleaned up other TRUSTBOT processes');
} catch (error) {
console.log('ℹ️ [MAIN.JS] No other TRUSTBOT processes found to clean up');
}
try {
console.log('🔧 [MAIN.JS] Killing lingering node.exe processes...');
execSync(`taskkill /f /im node.exe /fi "PID ne ${ourPid}"`, { stdio: 'ignore' });
console.log('✅ [MAIN.JS] Cleaned up node processes');
} catch (error) {
console.log('ℹ️ [MAIN.JS] No node processes found to clean up');
}
try {
console.log('🔧 [MAIN.JS] Killing lingering cmd.exe processes...');
execSync(`taskkill /f /im cmd.exe`, { stdio: 'ignore' });
console.log('✅ [MAIN.JS] Cleaned up cmd processes');
} catch (error) {
console.log('ℹ️ [MAIN.JS] No cmd processes found to clean up');
}
}
console.log('🎉 [MAIN.JS] Window close cleanup completed');
} catch (error) {
console.error('❌ [MAIN.JS] Error during window close cleanup:', error.message);
}
// 🎯 FINAL STEP: Centralized TRUSTBOT cleanup
performFinalTrustbotCleanup();
mainWindow = null;
});
// Handle window minimize/maximize
mainWindow.on('minimize', (event) => {
if (process.platform === 'darwin') {
event.preventDefault();
mainWindow.hide();
}
});
}
// Function to run automatic ticker update in background
async function runAutomaticTickerUpdate() {
console.log('🚀 Starting automatic ticker update...');
// Single-flight guard: prevent concurrent runs
if (runAutomaticTickerUpdate.inProgress && runAutomaticTickerUpdate.currentPromise) {
console.log('⏳ Ticker update already in progress, joining existing promise');
return runAutomaticTickerUpdate.currentPromise;
}
// Different approach for packaged vs development
if (app.isPackaged) {
// In packaged app, spawn Electron as Node to run the ESM script reliably
let scriptPath;
// Check if we're in the app.asar context
if (__dirname.includes('app.asar')) {
// Use app.asar.unpacked path for ESM modules
scriptPath = path.join(__dirname.replace('app.asar', 'app.asar.unpacked'), 'ticker-updateNew.mjs');
} else {
scriptPath = path.join(__dirname, 'ticker-updateNew.mjs');
}
console.log(`🔍 Running ticker update script at: ${scriptPath}`);
console.log(`🔍 Current directory: ${__dirname}`);
// Check if the file exists before trying to fork it
if (!fs.existsSync(scriptPath)) {
console.error(`❌ Error: ticker update script not found at ${scriptPath}`);
// Try to find the script in alternative locations
const possibleLocations = [
path.join(process.resourcesPath, 'app.asar.unpacked', 'ticker-updateNew.mjs'),
path.join(process.resourcesPath, 'ticker-updateNew.mjs'),
path.join(app.getAppPath(), 'ticker-updateNew.mjs')
];
for (const location of possibleLocations) {
console.log(`🔍 Checking alternative location: ${location}`);
if (fs.existsSync(location)) {
scriptPath = location;
console.log(`✅ Found ticker update script at: ${scriptPath}`);
break;
}
}
if (!fs.existsSync(scriptPath)) {
console.error(`❌ Could not find ticker update script in any location`);
return;
}
}
// Use Electron binary as Node to execute ESM .mjs
const updateProcess = spawn(process.execPath, [scriptPath], {
cwd: app.getPath('userData'), // Write outputs (e.g., base.json) to userData
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }
});
// Track the process for cleanup
childProcesses.push(updateProcess);
let output = '';
let errorOutput = '';
let newTokensCount = 0;
// No IPC messages in spawn mode; rely on stdout parsing for progress if needed
// Handle errors in the fork process
updateProcess.on('error', (err) => {
console.error(`❌ [Ticker Update] Failed to start process: ${err.message}`);
errorOutput += `Failed to start process: ${err.message}\n`;
});
updateProcess.stdout.on('data', (data) => {
const chunk = data.toString();
output += chunk;
console.log(`[Ticker Update] ${chunk.trim()}`);
});
updateProcess.stderr.on('data', (data) => {
const chunk = data.toString();
errorOutput += chunk;
console.warn(`[Ticker Update Error] ${chunk.trim()}`);
});
// Wait for process to complete with timeout
runAutomaticTickerUpdate.inProgress = true;
runAutomaticTickerUpdate.currentPromise = new Promise((resolve, reject) => {
const timeoutMs = 60 * 1000; // 60 seconds safety timeout
const timer = setTimeout(() => {
try {
console.warn('⏰ [Ticker Update] Timeout reached, killing process');
updateProcess.kill('SIGKILL');
} catch {}
}, timeoutMs);
updateProcess.on('close', (code) => {
// Remove from tracking array
const index = childProcesses.indexOf(updateProcess);
if (index > -1) {
childProcesses.splice(index, 1);
}
console.log(`✅ Ticker update completed with exit code: ${code}`);
if (code === 0) {
console.log(`📊 Token database updated successfully - ${newTokensCount} new tokens`);
// Send success notification to renderer if window exists
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('ticker-update-completed', {
success: true,
message: `Token database updated - ${newTokensCount} new tokens added`
});
}
clearTimeout(timer);
runAutomaticTickerUpdate.inProgress = false;
runAutomaticTickerUpdate.currentPromise = null;
resolve();
} else {
console.error('❌ Ticker update failed with code:', code);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('ticker-update-completed', {
success: false,
message: 'Failed to update token database',
error: errorOutput || 'Unknown error'
});
}
clearTimeout(timer);
runAutomaticTickerUpdate.inProgress = false;
runAutomaticTickerUpdate.currentPromise = null;
reject(new Error(`Ticker update failed with code ${code}`));
}
});
});
return runAutomaticTickerUpdate.currentPromise;
} else {
// In development, use npm script
const updateProcess = spawn('npm', ['run', 'ticker:updateNew'], {
cwd: __dirname,
stdio: ['pipe', 'pipe', 'pipe'],
shell: true
});
// Track the process for cleanup
childProcesses.push(updateProcess);
let output = '';
let errorOutput = '';
updateProcess.stdout.on('data', (data) => {
const chunk = data.toString();
output += chunk;
// Log ticker update progress (can be seen in dev console)
console.log(`[Ticker Update] ${chunk.trim()}`);
});
updateProcess.stderr.on('data', (data) => {
const chunk = data.toString();
errorOutput += chunk;
console.warn(`[Ticker Update Error] ${chunk.trim()}`);
});
// Return a promise that resolves/rejects on process completion with timeout
runAutomaticTickerUpdate.inProgress = true;
runAutomaticTickerUpdate.currentPromise = new Promise((resolve, reject) => {
const timeoutMs = 60 * 1000; // 60 seconds safety timeout
const timer = setTimeout(() => {
try {
console.warn('⏰ [Ticker Update] Timeout reached, killing process');
updateProcess.kill('SIGKILL');
} catch {}
}, timeoutMs);
updateProcess.on('close', (code) => {
// Remove from tracking array
const index = childProcesses.indexOf(updateProcess);
if (index > -1) {
childProcesses.splice(index, 1);
}
console.log(`✅ Ticker update completed with exit code: ${code}`);
if (code === 0) {
console.log('📊 Token database updated successfully');
// Send success notification to renderer if window exists
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('ticker-update-completed', {
success: true,
message: 'Token database updated successfully',
output: output
});
}
clearTimeout(timer);
runAutomaticTickerUpdate.inProgress = false;
runAutomaticTickerUpdate.currentPromise = null;
resolve();
} else {
console.error('❌ Ticker update failed with error output:', errorOutput);
// Send error notification to renderer if window exists
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('ticker-update-completed', {
success: false,
message: 'Failed to update token database',
error: errorOutput
});
}
clearTimeout(timer);
runAutomaticTickerUpdate.inProgress = false;
runAutomaticTickerUpdate.currentPromise = null;
reject(new Error(`Ticker update failed with code ${code}`));
}
});
// Handle process spawn errors in development mode
updateProcess.on('error', (error) => {
// Remove from tracking array
const index = childProcesses.indexOf(updateProcess);
if (index > -1) {
childProcesses.splice(index, 1);
}
console.error('❌ Failed to start ticker update:', error.message);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('ticker-update-completed', {
success: false,
message: 'Failed to start token database update',
error: error.message
});
}
clearTimeout(timer);
runAutomaticTickerUpdate.inProgress = false;
runAutomaticTickerUpdate.currentPromise = null;
reject(error);
});