This repository has been archived by the owner on Mar 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1837 lines (1551 loc) · 71.3 KB
/
index.js
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
/* Main app logic. */
const electron = require('electron')
const {app, BrowserWindow, dialog, ipcMain, shell} = electron
const os = require('os')
const path = require('path')
const url = require('url')
const fs = require('fs')
const util = require('util')
const unhandled = require('electron-unhandled')
const delayedCall = require('delayed-call')
const winston = require('winston')
const Transport = require('winston-transport')
const {createLogger, format, transports} = winston
const {combine, timestamp, prettyPrint} = format
const Store = require('electron-store')
const smartcashapi = require('./smartcashapi')
const debugUtils = require('./debug-utils')
const {watch} = require('melanke-watchjs')
const baseLogPath = "logs"
const sysLogsPath = baseLogPath + path.sep + 'system'
const userLogsPath = baseLogPath + path.sep + 'user'
const isDev = require('electron-is-dev')
require('electron-debug')({showDevTools: true})
let splashScreen, bgWin, modal, modalType, logFile, db, savedAppData
// create a custom transport to save winston logs into a json database using electron store
module.exports = {
JsonDBTransport: class JsonDBTransport extends Transport {
constructor(options) {
super(options)
if (options.label === "exception") {
// exceptions log
this.logDBExceptions = new Store({name: options.filename})
if (this.logDBExceptions.get('log') === undefined)
this.logDBExceptions.set('log', [])
}
else if (options.label === "system") {
// system log
this.logDBSystem = new Store({name: options.filename})
//console.log(this.logDBSystem)
if (this.logDBSystem.get('log') === undefined)
this.logDBSystem.set('log', [])
}
else if (options.label === "user") {
// user log
this.logDBUser = new Store({name: options.filename})
//console.log(this.logDBUser)
if (this.logDBUser.get('log') === undefined)
this.logDBUser.set('log', [])
}
}
log(info, callback) {
var self = this
setImmediate(function () {
self.emit('logged', info)
})
var logDB
//console.log(info)
//console.log(self)
if (self.logDBSystem !== undefined)
logDB = self.logDBSystem
else if (self.logDBExceptions !== undefined)
logDB = self.logDBExceptions
else if (self.logDBUser !== undefined)
logDB = self.logDBUser
if (logDB !== undefined) {
var log = logDB.get('log')
log.push(info)
logDB.set('log', log)
}
if (callback && typeof callback === "function")
callback()
}
}
}
// init various things before the main window loads
function appInit() {
// global task status object to be used in the renderer
global.taskStatus = new Map()
global.rpcFunctionDelay = 4000
global.explorerFunctionDelay = 5500
// fee tiers for SmartCash transactions, based on number of promo wallets
var txFeeTiers = {
"1-10": 0.001,
"11-50": 0.01,
"51-100": 0.02,
"101-200": 0.03,
"201-300": 0.04,
"301-400": 0.05,
"401-500": 0.06
}
// global object to be shared amongst renderer processes
global.sharedObject = {
config: null,
version: null,
txBaseFee: 0.001, // minimum transaction fee
txFeeTiers: txFeeTiers,
explorerCheckInterval: 1.2, // minimum time between block explorer requests
win: null,
logger: null,
sysLogger: null,
exceptionLogger: null,
isOnline: false,
referrer: "",
coreRunning: false,
coreError: false,
rpcConnected: false,
rpcError: false,
coreSynced: false,
coreSyncError: false,
blockExplorerError: false
}
// watch for changes on the shared object
watch(global.sharedObject, function(property, action, newValue, oldValue) {
//console.log(property)
//console.log(oldValue)
//console.log(newValue)
//console.log()
var infoMsg = false
var errorMsg = false
var msg = ""
if (global.sharedObject.win) {
if (property === "isOnline") {
global.sharedObject.win.webContents.send('onlineCheckAPP', {isOnline: global.sharedObject.isOnline})
if (global.sharedObject.isOnline) {
global.sharedObject.win.webContents.send('isOnline')
infoMsg = true
msg = "Is online"
}
else {
errorMsg = true
msg = "Not online"
}
}
else if (property === "coreRunning") {
global.sharedObject.win.webContents.send('coreCheckAPP', {coreRunning: global.sharedObject.coreRunning})
global.sharedObject.win.webContents.send('coreRunning')
infoMsg = true
msg = "Node client is running"
}
else if (property === "coreError") {
global.sharedObject.win.webContents.send('coreCheckAPP', {coreError: global.sharedObject.coreError})
global.sharedObject.win.webContents.send('coreError')
errorMsg = true
msg = "Node client not running"
}
else if (property === "rpcConnected") {
global.sharedObject.win.webContents.send('rpcCheckAPP', {rpcConnected: global.sharedObject.rpcConnected})
global.sharedObject.win.webContents.send('rpcConnected')
infoMsg = true
msg = "RPC connection made"
}
else if (property === "rpcError") {
global.sharedObject.win.webContents.send('rpcCheckAPP', {rpcError: global.sharedObject.rpcError})
global.sharedObject.win.webContents.send('rpcError')
}
else if (property === "coreSynced") {
global.sharedObject.win.webContents.send('coreSyncCheckAPP', {coreSynced: global.sharedObject.coreSynced})
global.sharedObject.win.webContents.send('coreSynced')
infoMsg = true
msg = "Node client synced"
}
else if (property === "coreSyncError") {
global.sharedObject.win.webContents.send('coreSyncCheckAPP', {coreSyncError: global.sharedObject.coreSyncError})
global.sharedObject.win.webContents.send('coreSyncError')
errorMsg = true
msg = "Node client sync error"
}
else if (property === "blockExplorerError") {
global.sharedObject.win.webContents.send('blockExplorerErrorAPP', {blockExplorerError: global.sharedObject.blockExplorerError})
}
if (infoMsg)
global.sharedObject.sysLogger.info(msg)
else if (errorMsg)
global.sharedObject.sysLogger.error(msg)
}
}, 0, true)
// send a notice to renderers when availableProjects is updated
watch(global.availableProjects, function(property, action, newValue, oldValue) {
if (global.sharedObject.win)
global.sharedObject.win.webContents.send('projectsReady')
})
global.referrer = ""
global.apiCallbackInfo = new Map() // keeps track of API callback vars per function call
// app config
ipcMain.setMaxListeners(0) // set max listeners to unlimited
loadProjects()
loadInternalData()
// setup logging
logFile = getCurrentDate()
/* from: https://github.com/winstonjs/winston/issues/1243#issuecomment-411360908 */
const formatErrorConverter = format(info =>
info instanceof Error
? Object.assign({ level: info.level, message: info.message, stack: info.stack }, info)
: info,
)
const formatErrorConverterInstance = formatErrorConverter();
// system logger for info and error
winston.loggers.add('sysLogger', {
format: combine(timestamp(), prettyPrint(), formatErrorConverterInstance),
transports: [
new module.exports.JsonDBTransport({filename: path.join(sysLogsPath, logFile), level: 'info', label: 'system'})
],
exitOnError: false
})
// unhandled exception logger
winston.loggers.add('exceptionLogger', {
format: combine(timestamp(), prettyPrint(), formatErrorConverterInstance),
transports: [
new module.exports.JsonDBTransport({filename: path.join(sysLogsPath, logFile+'_exceptions'), level: 'error', label: 'exception'})
],
exitOnError: false
})
// user action logger
winston.loggers.add('logger', {
format: combine(timestamp(), prettyPrint()),
transports: [
new module.exports.JsonDBTransport({filename: path.join(userLogsPath, logFile), level: 'info', label: 'user'})
],
exitOnError: false
})
global.sharedObject.sysLogger = winston.loggers.get('sysLogger')
global.sharedObject.sysLogger.emitErrs = true
global.sharedObject.exceptionLogger = winston.loggers.get('exceptionLogger')
global.sharedObject.exceptionLogger.emitErrs = true
global.sharedObject.logger = winston.loggers.get('logger')
global.sharedObject.logger.emitErrs = true
// catch unhandled exceptions
unhandled({
logger: function(err) {
global.sharedObject.exceptionLogger.error(err.stack)
// the "EPERM operation not permitted error" is fatal (https://github.com/sindresorhus/electron-store/issues/31)
if (err.message.indexOf('EPERM') != -1) {
var content = {
text: {
title: 'Error',
body: 'SmartSweeper has encountered a fatal error. The app will now close.'
},
fatal: true
}
createDialog(null, global.sharedObject.win, "error", content.text, content.fatal)
}
},
showDialog: true
})
//if (isDev)
//global.sharedObject.logger.add(new transports.Console({format: format.simple()}))
}
// load the project db or create it if it doesn't exist
// saved in %APPDATA%/smart-sweeper on Win
// saved in $XDG_CONFIG_HOME/smart-sweeper or ~/.config/smart-sweeper on Linux
// saved in ~/Library/Application Support/smart-sweeper on Mac
function loadProjects() {
db = new Store({name: "smart-sweeper"})
global.availableProjects = db.get('projects')
if (global.availableProjects === undefined) {
db.set('projects', {index: 0, list: []})
global.availableProjects = db.get('projects')
}
}
// load the internal data or create it if it doesn't exist
// saved in %APPDATA%/smart-sweeper on Win
// saved in $XDG_CONFIG_HOME/smart-sweeper or ~/.config/smart-sweeper on Linux
// saved in ~/Library/Application Support/smart-sweeper on Mac
function loadInternalData() {
try {
savedAppData = new Store({name: "smart-sweeper-data"})
global.savedAppData = savedAppData.get('data')
if (global.savedAppData === undefined) {
savedAppData.set('data', {
availableBalanceTotal: 0,
pendingFundsTotal: 0,
pendingWalletsTotal: 0,
confirmedFundsTotal: 0,
confirmedWalletsTotal: 0,
claimedFundsTotal: 0,
claimedWalletsTotal: 0,
sweptFundsTotal: 0,
sweptWalletsTotal: 0
})
global.savedAppData = savedAppData.get('data')
}
}
catch(err) {
createDialog(null, global.sharedObject.win, "error", err, true)
}
}
// some code from: https://github.com/trodi/electron-splashscreen
function createSplashScreen() {
// set up splash screen
const splashScreenConfig = {
backgroundColor: '#FFF',
width: 365,
height: 365,
frame: false,
center: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
devTools: false,
nodeIntegration: true,
},
show: false
}
splashScreen = new BrowserWindow(splashScreenConfig)
splashScreen.loadURL(url.format({
pathname: path.join(__dirname, 'app', 'utils', 'splash.html'),
protocol: 'file',
slashes: true
}))
splashScreen.on("ready-to-show", () => {
splashScreen.show()
})
}
function closeSplashScreen() {
if (splashScreen) {
splashScreen.close()
splashScreen = null
global.sharedObject.win.maximize()
global.sharedObject.win.show()
}
}
// create the background window used to run async tasks
function createBgWindow() {
const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize
const windowConfig = {
title: "",
width: 800,
height: 700,
center: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
devTools: true
},
show: false
}
// Create the browser window.`
bgWin = new BrowserWindow(windowConfig)
bgWin.loadURL(url.format({
pathname: path.join(__dirname, 'background', 'background.html'),
protocol: 'file',
slashes: true
}))
bgWin.setMenu(null)
bgWin.on("ready-to-show", () => {
setTimeout(function() {
closeSplashScreen()
//bgWin.show()
}, 12000)
})
bgWin.on('show', () => {
//bgWin.openDevTools()
})
bgWin.on('closed', () => {
bgWin = null
})
}
// create the main window
function createWindow() {
var icon
if (os.platform() === "win32")
icon = 'icon.ico'
else if (os.platform() === "darwin")
icon = 'icon.icns'
else if (os.platform() === "linux")
icon = 'icon512x512.png'
const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize
const windowConfig = {
title: "SmartSweeper",
width: width, //1000,
height: height, //600,
center: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
devTools: true
},
icon: path.join(__dirname, 'images', 'icons', icon),
show: false
}
// Create the browser window.
global.sharedObject.win = new BrowserWindow(windowConfig)
global.sharedObject.win.setMenu(null)
// and load the index.html of the app.
global.sharedObject.win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file',
slashes: true
}))
global.sharedObject.win.on("ready-to-show", () => {
})
global.sharedObject.win.on('show', () => {
if (global.sharedObject.win) {
//global.sharedObject.win.webContents.openDevTools()
global.sharedObject.win.webContents.send('projectsReady')
}
})
// Emitted when the window is closed.
global.sharedObject.win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
if (bgWin) {
bgWin.close()
bgWin = null
global.sharedObject.win = null
}
})
}
// create a modal
function createModal(type, text) {
var parent, title, width, height, pathname, resizable, minimizable, maximizable, alwaysOnTop, fullscreenable
winBounds = global.sharedObject.win.getBounds()
if (type === "edit") {
title = "Edit Project '" + global.activeProject.name + "'"
parent = global.sharedObject.win
width = Math.ceil(winBounds.width - (winBounds.width*0.6))
height = Math.ceil(winBounds.height - (winBounds.height*0.15))
pathname = path.join(__dirname, 'app', 'utils', 'editModal.html')
resizable = true
minimizable = true
maximizable = true
alwaysOnTop = false
fullscreenable = true
}
else if (type === "paperWallets") {
title = "Paper Wallets for Project '" + global.activeProject.name + "'"
parent = global.sharedObject.win
width = 1000
//width = Math.ceil(winBounds.width - (winBounds.width*0.52))
height = winBounds.height
pathname = path.join(__dirname, 'app', 'fund', 'paperWallet.html')
resizable = true
minimizable = true
maximizable = true
alwaysOnTop = false
fullscreenable = true
}
else if (type === "fund") {
title = "Fund Project '" + global.activeProject.name + "'"
parent = global.sharedObject.win
width = Math.ceil(winBounds.width - (winBounds.width*0.35))
height = Math.ceil(winBounds.height - (winBounds.height*0.15))
pathname = path.join(__dirname, 'app', 'fund', 'fundModal.html')
resizable = true
minimizable = true
maximizable = true
alwaysOnTop = false
fullscreenable = true
}
if (modal)
return;
modal = new BrowserWindow({
title: title,
width: width,
height: height,
resizable: resizable,
minimizable: minimizable,
maximizable: maximizable,
alwaysOnTop: alwaysOnTop,
fullscreenable: fullscreenable,
parent: parent,
modal: true,
show: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
modal.setMenu(null)
modal.loadURL(url.format({
pathname: pathname,
protocol: 'file:',
slashes: true
}))
modal.once('ready-to-show', () => {
if (type === "paperWallets")
modal.webContents.send('paperWalletsModal', {project: global.activeProject})
modal.show()
})
modal.on('closed', () => {
modal = null
})
}
function createDialog(event, window, type, text, fatal = false) {
var buttons
if (type === 'question')
buttons = ['OK', 'Cancel']
else if (type === 'info' || type === 'error')
buttons = ['OK']
dialog.showMessageBox(window, {
type: type,
buttons: buttons,
title: text.title,
message: text.body
}, function(resp) {
if (event != null) {
if (resp == 0) {
if (modal === undefined || modal == null)
event.sender.send('dialogYes')
else
window.webContents.send('dialogYes')
}
else {
if (modal === undefined || modal == null)
event.sender.send('dialogNo')
else
window.webContents.send('dialogNo')
}
}
if (fatal)
app.quit()
})
}
/* Generic API callback function. */
let apiCallback = function(resp, functionName, projectInfo) {
var referrer = projectInfo.referrer
var apiCallbackInfo
if ((referrer.indexOf('getProjectAddressInfo') == -1) && (referrer.indexOf('getProjectTxStatus') == -1))
apiCallbackInfo = global.apiCallbackInfo.get(referrer)
else
apiCallbackInfo = global.apiCallbackInfo.get(referrer+projectInfo.projectID)
if (debugUtils.DEBUG && referrer.indexOf('getClaimedFundsInfo') != -1) {
debugUtils.debugSave('functionName: ' + functionName)
debugUtils.debugSave('referrer: ' + referrer)
debugUtils.debugSave('apiCallbackInfo: ' + util.inspect(global.apiCallbackInfo.get(referrer), {depth: null}))
debugUtils.debugSave('apiCallbackInfo: ' + util.inspect(apiCallbackInfo, {depth: null}))
debugUtils.debugSave('projectInfo: ' + util.inspect(projectInfo, {depth: null}))
debugUtils.debugSave(resp.type)
debugUtils.debugSave(resp.msg)
}
if (apiCallbackInfo !== undefined) {
if (resp.type === "data") {
if (projectInfo.projectName) {
var address = ""
if (projectInfo.address) {
address = ", wallet address: " + projectInfo.address
}
else if (projectInfo.addrIndex) {
address = ", wallet address: " + global.availableProjects.list[projectInfo.projectIndex].recvAddrs[projectInfo.addrIndex].publicKey
}
global.sharedObject.sysLogger.info(referrer + ' - ' + functionName + ', project: ' + projectInfo.projectName + address)
}
else if (projectInfo.address)
global.sharedObject.sysLogger.info(referrer + ' - ' + functionName + ', wallet address: ' + projectInfo.address)
else if (projectInfo.projectID)
global.sharedObject.sysLogger.info(referrer + ' - ' + functionName + ', project #' + projectInfo.projectID)
else
global.sharedObject.sysLogger.info(referrer + ' - ' + functionName)
if (functionName === "checkBalance") {
global.sharedObject.blockExplorerError = false
if (referrer === "checkProjectBalances") {
global.availableProjects.list[projectInfo.projectIndex].currentFunds = resp.msg
if (resp.msg == 0)
global.availableProjects.list[projectInfo.projectIndex].zeroBalance = true
db.set('projects', global.availableProjects)
}
else if (referrer === "getClaimedFundsInfo") {
if (global.availableProjects.list[projectInfo.projectIndex].recvAddrs[projectInfo.addrIndex].txConfirmed &&
!global.availableProjects.list[projectInfo.projectIndex].recvAddrs[projectInfo.addrIndex].swept &&
(resp.msg == 0)) {
global.availableProjects.list[projectInfo.projectIndex].recvAddrs[projectInfo.addrIndex].claimed = true
apiCallbackInfo.claimedFunds += projectInfo.addrAmt
apiCallbackInfo.claimedWallets++
}
else {
global.availableProjects.list[projectInfo.projectIndex].recvAddrs[projectInfo.addrIndex].claimed = false
}
}
else if (referrer === "getSweptFundsInfo") {
if (resp.msg == 0)
global.availableProjects.list[projectInfo.projectIndex].recvAddrs[projectInfo.addrIndex].swept = true
}
}
else if (functionName === "checkTransaction") {
if (referrer === "checkFundingTxids") {
var obj = {}
resp.msg.vout.forEach(function(tx, key) {
if (tx.scriptPubKey.addresses.includes(projectInfo.address)) {
if (resp.msg.confirmations >= 6) {
obj[projectInfo.txid] = {confirmed: true, confirmations: resp.msg.confirmations}
apiCallbackInfo.balance += tx.value
}
else {
obj[projectInfo.txid] = {confirmed: false, confirmations: resp.msg.confirmations}
}
apiCallbackInfo.txInfo.push(obj)
}
})
}
else if (referrer === "checkAvailProjectBalances") {
if (resp.msg.confirmations >= 6 && !projectInfo.fundsSent) {
resp.msg.vout.forEach(function(tx, key) {
if (tx.scriptPubKey.addresses.includes(projectInfo.address)) {
apiCallbackInfo.total += tx.value
}
})
}
}
else if (referrer.indexOf('getProjectTxStatus') != -1) {
var obj = {}
resp.msg.vout.forEach(function(tx, key) {
if (tx.scriptPubKey.addresses.includes(projectInfo.address)) {
if (resp.msg.confirmations >= 6) {
obj[projectInfo.txid] = {confirmed: true, confirmations: resp.msg.confirmations}
apiCallbackInfo.balance += tx.value
apiCallbackInfo.confirmedTxs++
}
else {
obj[projectInfo.txid] = {confirmed: false, confirmations: resp.msg.confirmations}
}
apiCallbackInfo.txInfo.push(obj)
}
})
}
else if (referrer === "getSweptTxStatus") {
if (resp.msg.confirmations >= 6)
global.availableProjects.list[projectInfo.projectIndex].sweepTxConfirmed = true
}
else if (referrer === "getWalletTxStatus") {
var totalAddresses = global.availableProjects.list[projectInfo.projectIndex].recvAddrs.length
if (resp.msg.confirmations < 6) {
apiCallbackInfo.pendingFunds += (projectInfo.addrAmt * totalAddresses)
apiCallbackInfo.pendingWallets += totalAddresses
}
else {
apiCallbackInfo.confirmedFunds += (projectInfo.addrAmt * totalAddresses)
apiCallbackInfo.confirmedWallets += totalAddresses
}
global.availableProjects.list[projectInfo.projectIndex].recvAddrs.forEach(function(address, addrKey) {
address.confirmations = resp.msg.confirmations
if (resp.msg.confirmations < 6)
address.txConfirmed = false
else
address.txConfirmed = true
})
}
}
else if (functionName === "getAddressInfo") {
if (referrer.indexOf('getProjectAddressInfo') != -1) {
apiCallbackInfo.txs = resp.msg.transactions
}
}
else if (functionName === "sendFunds") {
if (referrer === "fundProject") {
apiCallbackInfo.validTx = true
apiCallbackInfo.msg = "Success. Project information updated."
}
else if ((referrer === "sendPromotionalFunds")) {
global.availableProjects.list[projectInfo.projectIndex].recvAddrs.forEach(function(address, key) {
address.sentTxid = resp.msg
address.txConfirmed = false
address.confirmations = 0
});
}
}
else if (functionName === "sweepFunds") {
global.availableProjects.list[projectInfo.projectIndex].sweepTxid = resp.msg
global.availableProjects.list[projectInfo.projectIndex].sweepTxConfirmed = false
global.availableProjects.list[projectInfo.projectIndex].fundsSwept = true
db.set('projects', global.availableProjects)
}
// once all of the projects/promotional wallets have been processed, send data back to the initiator
//console.log('apiCallbackInfo.apiCallbackCounter: ', apiCallbackInfo.apiCallbackCounter)
apiCallbackInfo.apiCallbackCounter++
var apiCallbackCounter = apiCallbackInfo.apiCallbackCounter
if (functionName === "checkBalance") {
if ((referrer === "getClaimedFundsInfo") && (apiCallbackCounter == apiCallbackInfo.totalAddrs)) {
// store the claimed funds and claimed wallets total in a data file
global.savedAppData.claimedFundsTotal = apiCallbackInfo.claimedFunds
global.savedAppData.claimedWalletsTotal = apiCallbackInfo.claimedWallets
savedAppData.set('data', global.savedAppData)
// calculate the number of claimed wallets per project
var claimed
global.availableProjects.list.forEach(function(project, projectKey) {
claimed = 0
if (project.fundsSent && !project.fundsSwept) {
project.recvAddrs.forEach(function(address, addressKey) {
if (address.claimed)
claimed++
})
}
project.claimedAddr = claimed
if (project.claimedAddr == project.recvAddrs.length)
project.allClaimed = true
else
project.allClaimed = false
})
db.set('projects', global.availableProjects)
if (global.sharedObject.win) {
global.sharedObject.win.webContents.send('projectsReady')
global.sharedObject.win.webContents.send('claimedFundsInfo', {claimedFunds: apiCallbackInfo.claimedFunds, claimedWallets: apiCallbackInfo.claimedWallets})
}
global.apiCallbackInfo.delete(referrer)
}
else if ((referrer === "getSweptFundsInfo") && (apiCallbackCounter == apiCallbackInfo.totalAddrs)) {
var totalSweptFunds = 0
var projectSweptFunds
var sweptWalletsCount = 0
global.availableProjects.list.forEach(function(project, projectKey) {
projectSweptFunds = 0
if (project.fundsSwept) {
project.recvAddrs.forEach(function(address, addrKey) {
if (address.swept) {
projectSweptFunds += project.addrAmt
sweptWalletsCount++
}
})
var txFee = getTxFee(sweptWalletsCount)
totalSweptFunds = totalSweptFunds + (projectSweptFunds - txFee)
}
});
db.set('projects', global.availableProjects)
// store the swept funds and swept wallets total in a data file
global.savedAppData.sweptFundsTotal = totalSweptFunds
global.savedAppData.sweptWalletsTotal = sweptWalletsCount
savedAppData.set('data', global.savedAppData)
if (global.sharedObject.win) {
global.sharedObject.win.webContents.send('projectsReady')
global.sharedObject.win.webContents.send('sweptFundsInfo', {sweptFunds: totalSweptFunds, sweptWalletsCount: sweptWalletsCount})
}
global.apiCallbackInfo.delete(referrer)
}
}
else if (functionName === "checkTransaction") {
if (referrer === "checkFundingTxids" && (apiCallbackCounter == apiCallbackInfo.txCount)) {
var confirmedCounter = 0
var txids = []
apiCallbackInfo.txInfo.forEach(function(tx, key) {
txids.push(tx)
if (Object.values(tx)[0])
confirmedCounter++
})
global.availableProjects.list[projectInfo.projectIndex].txid = txids
if (confirmedCounter == apiCallbackInfo.txInfo.length) {
global.availableProjects.list[projectInfo.projectIndex].originalFunds = apiCallbackInfo.balance
global.availableProjects.list[projectInfo.projectIndex].txConfirmed = true
}
else {
global.availableProjects.list[projectInfo.projectIndex].txConfirmed = false
}
db.set('projects', global.availableProjects)
if (global.sharedObject.win) {
global.sharedObject.win.webContents.send('projectsReady')
if (modal) {
modal.webContents.send('fundingTxidsChecked', {msgType: 'data', confirmed: global.availableProjects.list[projectInfo.projectIndex].txConfirmed, txInfo: apiCallbackInfo.txInfo, balance: apiCallbackInfo.balance})
}
else {
global.sharedObject.win.webContents.send('projectsReady')
}
}
global.apiCallbackInfo.delete(referrer)
}
else if ((referrer === "checkAvailProjectBalances") && (apiCallbackCounter == apiCallbackInfo.totalTxs)) {
global.taskStatus.set('checkAvailProjectBalances', {status: true, error: false})
global.savedAppData.availableBalanceTotal = apiCallbackInfo.total
savedAppData.set('data', global.savedAppData)
db.set('projects', global.availableProjects)
if (global.sharedObject.win) {
global.sharedObject.win.webContents.send('projectsReady')
global.sharedObject.win.webContents.send('balancesChecked', {availableBalance: apiCallbackInfo.total})
}
global.apiCallbackInfo.delete(referrer)
}
else if ((referrer.indexOf('getProjectTxStatus') != -1) && (apiCallbackCounter == apiCallbackInfo.totalTxs)) {
global.availableProjects.list[projectInfo.projectIndex].txid = apiCallbackInfo.txInfo
global.availableProjects.list[projectInfo.projectIndex].originalFunds = apiCallbackInfo.balance
// check the total num of confirmed tx for each project against the total number of funding txids
if (apiCallbackInfo.confirmedTxs == apiCallbackInfo.txInfo.length)
global.availableProjects.list[projectInfo.projectIndex].txConfirmed = true
else
global.availableProjects.list[projectInfo.projectIndex].txConfirmed = false
db.set('projects', global.availableProjects)
if (global.sharedObject.win)
global.sharedObject.win.webContents.send('projectsReady')
global.apiCallbackInfo.delete(referrer+projectInfo.projectID)
}
else if (referrer === "getSweptTxStatus" && (apiCallbackCounter == apiCallbackInfo.totalSweptProjects)) {
db.set('projects', global.availableProjects)
if (global.sharedObject.win)
global.sharedObject.win.webContents.send('projectsReady')
global.apiCallbackInfo.delete(referrer)
}
else if (referrer === "getWalletTxStatus" && (apiCallbackCounter == apiCallbackInfo.totalFundedProjects)) {
// store the info in a data file
global.savedAppData.pendingFundsTotal = apiCallbackInfo.pendingFunds
global.savedAppData.pendingWalletsTotal = apiCallbackInfo.pendingWallets
global.savedAppData.confirmedFundsTotal = apiCallbackInfo.confirmedFunds
global.savedAppData.confirmedWalletsTotal = apiCallbackInfo.confirmedWallets
savedAppData.set('data', global.savedAppData)
db.set('projects', global.availableProjects)
if (global.sharedObject.win) {
global.sharedObject.win.webContents.send('allTxInfo', {pendingFunds: apiCallbackInfo.pendingFunds, pendingWallets: apiCallbackInfo.pendingWallets, confirmedFunds: apiCallbackInfo.confirmedFunds, confirmedWallets: apiCallbackInfo.confirmedWallets})
global.sharedObject.win.webContents.send('projectsReady')
}
global.apiCallbackInfo.delete(referrer)
}
}
else if (functionName === "getAddressInfo") {
if (referrer === "getProjectAddressInfo" && apiCallbackInfo !== undefined) {
global.apiCallbackInfo.set('getProjectTxStatus'+projectInfo.projectID, {
apiCallbackCounter: 0,
totalTxs: apiCallbackInfo.txs.length,
txInfo: [],
confirmedTxs: 0,
balance: 0
})
apiCallbackInfo.txs.forEach(function(txid, txKey) {
delayedCall.create(global.rpcFunctionDelay, smartcashapi.checkTransaction, {referrer: "getProjectTxStatus", projectName: projectInfo.projectName, projectID: projectInfo.projectID, projectIndex: projectInfo.projectIndex, address: projectInfo.address, txid: txid}, apiCallback)
})
global.apiCallbackInfo.delete(referrer+projectInfo.projectID)
}
}
else if (functionName === "sendFunds") {
if ((referrer === "fundProject")) {
//global.availableProjects.list[projectInfo.projectIndex].projectFunded = true
global.availableProjects.list[projectInfo.projectIndex].zeroBalance = false
global.availableProjects.list[projectInfo.projectIndex].txConfirmed = false
global.apiCallbackInfo.delete(referrer)
db.set('projects', global.availableProjects)
if (modal)
modal.webContents.send('projectFunded', {validTx: apiCallbackInfo.validTx, msg: apiCallbackInfo.msg})
global.sharedObject.logger.info('Project "' + global.activeProject.name + '" was funded.')
refreshLogFile()
}
else if ((referrer === "sendPromotionalFunds")) {
global.sharedObject.logger.info('Funds were sent to promotional wallets for project "' + projectInfo.projectName + '".')
refreshLogFile()
global.availableProjects.list[projectInfo.projectIndex].fundsSent = true
db.set('projects', global.availableProjects)
if (global.sharedObject.win) {
global.sharedObject.win.webContents.send('projectsReady')
global.sharedObject.win.webContents.send('promotionalFundsSent', {msgType: 'data', msg: 'Funds were sent to promotional wallets for project "' + projectInfo.projectName + '".'})
}
global.apiCallbackInfo.delete(referrer)
}
}
else if ((functionName === "sweepFunds") && (apiCallbackCounter == apiCallbackInfo.totalProjects)) {
var projectNames = ""
apiCallbackInfo.projectNames.forEach(function(name, index) {
if (apiCallbackInfo.totalProjects == 1)
projectNames = name
else if (apiCallbackInfo.totalProjects == 2) {
if (index == 0)
projectNames = name
else
projectNames = projectNames + " and " + name
}
else {
if (index < apiCallbackInfo.projectNames.length-1)
projectNames = projectNames + ", " + name
else
projectNames = projectNames + ", and " + name
}
})
global.taskStatus.set('sweepFunds', {status: true, error: false})
global.sharedObject.logger.info('Funds were swept for project(s) "' + projectNames + '".')
refreshLogFile()
if (global.sharedObject.win) {
global.sharedObject.win.webContents.send('fundsSwept', {msgType: 'data', msg: 'Funds were swept for project(s) "' + projectNames + '".'})
}
}
}
else if (resp.type === "error") {
if (debugUtils.DEBUG) {
console.log('index.js error block: ')