-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStart.js
More file actions
491 lines (450 loc) · 15.3 KB
/
Start.js
File metadata and controls
491 lines (450 loc) · 15.3 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
// https://api.coinmarketcap.com/v1/ticker/shield-coin/
const Discord = require('discord.js') // 9.3.1
const Client = new Discord.Client()
const nosql = require('nosql')
const shield = require('./lib/shield')()
var fs = require('fs')
var request = require('request')
// IMPORTANT load backup if not exists
if (fs.existsSync('../uid.nosql')) {
fs.createReadStream('../uid.nosql').pipe(fs.createWriteStream('uid.nosql'))
}
// IMPORTANT load backup
var db = nosql.load('uid.nosql')
var Cmca = require('coinmarketcap-api')
var cmc = new Cmca()
const algos = ['x17', 'scrypt', 'myrgr', 'lyra2v2', 'blake2s']
var MessageQueue = []
var collectorAddr = 'SHIELDADDRESS' // must be on the same wallet
shield.auth('Macintyre, John', 'mypassword')
var jsonf
var btcval
function Update () {
// IMPORTANT create backup
fs.truncate('../uid.nosql', 0, function () {
fs.createReadStream('uid.nosql').pipe(fs.createWriteStream('../uid.nosql'))
})
// IMPORTANT create backup
cmc.getTicker({
limit: 1,
currency: 'shield-xsh'
}).then(x => {
jsonf = x
}).catch(console.log)
cmc.getTicker({
limit: 1,
currency: 'bitcoin'
}).then(x => {
btcval = x[0]['price_usd']
}).catch(console.log)
db.find().make(function (builder) { // Get All users
builder.callback(function (err, response) {
if (err) {
console.log(err)
}
response.forEach(function (element) { // Iterate through them
shield.getreceivedbyaddress(element['deposit_address'], function (err, inf) {
if (err) {
console.log(err)
return
}
if (inf > element['ActualBalance']) {
db.modify({
ActualBalance: inf
}).make(function (builder) {
builder.first() // --> modifies only one document
builder.where('deposit_address', element['deposit_address'])
builder.callback(function (err, count) {
if (err) {
console.log(err)
}
UpdateBalance(element['uid'], element['balance'] + (inf - element['ActualBalance'])) // add the diff of recieved coins
Client.channels.get('382625543993950209').sendMessage('<@' + String(element['uid']) + '> deposited ' + String(inf - element['ActualBalance']) + 'XSH')
})
})
}
})
}, this)
})
})
}
Update()
setInterval(Update, 30 * 1000) // every 30 sec
setInterval(() => {
// Safety back up, less often so it's not as easily overwriten
fs.truncate('../../uid.nosql', 0, function () {
fs.createReadStream('uid.nosql').pipe(fs.createWriteStream('../../uid.nosql'))
})
}, 5 * 60 * 1000)
// FIXME:Round Down when upgrading balances
function GetNewAddress () {
return new Promise(function (resolve, reject) {
let daddress
shield.getNewAddress(function (err, address) {
if (err) {
reject(err)
return
}
this.validateaddress(address, function (err, info) {
if (err) {
reject(err)
return
}
daddress = address
resolve(daddress)
})
})
})
}
function GetFromUID (uid) {
return new Promise(function (resolve, reject) {
db.find().make(function (filter) {
filter.first()
filter.where('uid', '=', uid)
filter.callback(function (err, response) {
if (err) {
reject(err)
} else {
if (response === undefined) {
reject("can't find user")
}
resolve(response)
}
})
})
})
}
function UpdateBalance (uid, newBalance) {
db.modify({
balance: newBalance
}).make(function (builder) {
builder.first() // --> modifies only one document
builder.where('uid', uid)
builder.callback(function (err, count) {
if (err) {
console.log(err)
}
console.log('update balance: ' + uid + '; ' + String(newBalance))
})
})
}
function GetBalance (uid) {
return new Promise(function (resolve, reject) {
GetFromUID(uid).then(x => {
resolve(x['balance'])
}).catch(err => {
reject(err)
})
})
}
// TODO: implement withdraw addresses
function WithdrawBalance (uid, address, amount) {
return new Promise(function (resolve, reject) {
GetBalance(uid).then(balance => {
if (balance >= amount) {
amount -= 0.05 // Tx fee
console.log('withdrawing', address, amount)
shield.exec('sendToAddress', address, amount, function (err, txid) {
if (err) {
reject(err)
return
}
GetBalance(uid).then(balance => {
GetBalance('MainAddr').then(Mainbalance => {
UpdateBalance(uid, balance - (amount + 0.05))
})
})
resolve(txid)
})
} else {
reject('`not enough balance`')
}
}).catch(err => {
reject(err)
})
})
}
/* Returns deposit Addr or undefined */
function AddNewUser (uid) {
return new Promise(function (resolve, reject) {
GetFromUID(uid).then(response => {
resolve(response['deposit_address'])
}).catch(x => {
GetNewAddress().then(Naddr => {
db.insert({
uid: uid,
balance: 0,
deposit_address: Naddr,
ActualBalance: 0
}).callback(function (err) {
if (err) {
reject(err)
return
}
resolve(Naddr)
})
}).catch(x => {
reject(x)
})
})
})
}
function SendMsg (MessageClass, MessageString) {
MessageClass.channel.sendMessage(MessageString).then(msg => {
MessageQueue.unshift(msg)
if (MessageQueue.length > 5) {
MessageQueue[4].delete()
MessageQueue.pop()
}
}).catch(x => {
console.log("Couldn't send message.")
})
}
GetBalance('MainAddr').then(balance => {
console.log('Main balance is:' + String(balance))
}).catch(x => {
AddNewUser('MainAddr').then(x => {
console.log('MainAddr address is: ' + x)
}).catch(x => {
console.log("Couldn't make address.", x)
})
console.log(x)
})
function RandomNumber () { // dist
return Math.random()
}
Client.on('ready', () => {
// console.log( "ColorChange bot has been started!" );
// Client.user.setGame( "SHIELDbot" );
Client.user.setStatus('online')
// var channel = Client.channels.get('general');
// channel.sendMessage("Back online! again..");
})
var InfoLast = 0
Client.on('message', Message => {
if (Message.author.bot) {
return
}
var content = Message.content.toLowerCase().split(/\s+/)
var mention = Array.from(Message.mentions.users.values())
if (content[0] === '!info' && new Date().getTime() > InfoLast + (1000 * 60 * 1) && (Message.channel.type === 'text')) { // wait five minutes interval at least
// console.log(jsonf);
var jsons = jsonf[0]
SendMsg(Message, 'XSH || ' + jsons['price_btc'] + ' BTC || $' + jsons['price_usd'] + ' || ' + jsons['percent_change_24h'] + '% || 24h vol: ' + (jsons['24h_volume_usd'] / btcval).toFixed(4) + ' BTC || CMC Rank: ' + jsons['rank'])
InfoLast = new Date().getTime()
}
if (content[0] === '!deposit' && (Message.channel.type === 'text')) {
GetFromUID(Message.author.id).then(user => {
SendMsg(Message, '<@' + String(Message.author.id) + '>, Your deposit address is:' + user['deposit_address'])
}).catch(err => {
console.log(err)
AddNewUser(Message.author.id).then(addr => {
SendMsg(Message, '<@' + String(Message.author.id) + '>, Your deposit address is: ' + addr)
})
})
}
if (content[0] === '!admin' && String(Message.author.id) === '262251841343979520') {
if (content[1] === 'checkinput') {
SendMsg(Message, JSON.stringify(mention[0].id) + JSON.stringify(content))
}
if (content[1] === 'generateuser') {
if (mention[0]) {
GetFromUID(mention[0].id).then(user => {
SendMsg(Message, '<@' + String(mention[0].id) + '>, Your deposit address is:' + user['deposit_address'])
}).catch(err => {
console.log(err)
AddNewUser(mention[0].id).then(addr => {
SendMsg(Message, '<@' + String(mention[0].id) + '>, Your deposit address is: ' + addr)
})
})
} else {
SendMsg(Message, "Didn't mention user")
}
}
return
}
if (content[0] === '!chance' && (Message.channel.type === 'text')) {
var amount = Number(content[1])
if (amount === undefined || isNaN(amount)) {
amount = 50 // default
}
if (amount < 10) {
SendMsg(Message, 'Minimum bet is 10XSH')
return
}
if (amount <= 0) {
SendMsg(Message, 'Smart ass >_>')
return
}
if (amount > 500) {
SendMsg(Message, 'Maximum bet is 500XSH')
return
}
GetBalance(Message.author.id).then(balance => {
GetBalance('MainAddr').then(Mainbalance => {
if (balance >= amount) {
if (RandomNumber() > 0.51) {
SendMsg(Message, '<@' + String(Message.author.id) + '>. Nice! You win ' + String(amount) + 'XSH!')
UpdateBalance(Message.author.id, balance + amount)
UpdateBalance('MainAddr', Mainbalance - amount)
} else {
SendMsg(Message, '<@' + String(Message.author.id) + '>. Bad luck! Try again next time!')
UpdateBalance(Message.author.id, balance - amount)
UpdateBalance('MainAddr', Mainbalance + amount)
}
} else {
// value for remaining required XSH (amount - balance) was not truncated.
// use the Math.ceil function
SendMsg(Message, 'Balance insufficient. (you need ' + (amount - balance).toFixed(3).replace(/\.?0*$/, '') + ' more XSH)')
}
})
}).catch(x => {
SendMsg(Message, 'Your XSH balance is empty. (Hint: use `!deposit`)')
})
}
if (content[0] === '!balance') {
GetBalance(Message.author.id).then(x => {
SendMsg(Message, '<@' + String(Message.author.id) + '>, You have: ' + String(x) + ' XSH')
}).catch(x => {
SendMsg(Message, 'Your XSH balance is empty. (Hint: use `!deposit`)')
})
}
if (content[0] === '!donate') {
var amount = Number(content[1])
if (amount === undefined || isNaN(amount)) {
SendMsg(Message, 'Please use `!donate <amount>`')
return
}
if (amount <= 0) {
SendMsg(Message, 'Smart ass >_>')
return
}
GetBalance(Message.author.id).then(balance => {
GetBalance('MainAddr').then(Mainbalance => {
if (balance < amount) {
SendMsg(Message, 'not enough balance')
return
}
UpdateBalance(Message.author.id, balance - amount)
UpdateBalance('MainAddr', Mainbalance + amount)
if (amount > 100000) {
SendMsg(Message, '<@' + String(Message.author.id) + '>, Thank you so much for your donation! You may choose a custom colour and title.')
} else {
SendMsg(Message, '<@' + String(Message.author.id) + '>, Thanks for the donation!')
}
})
}).catch(x => {
SendMsg(Message, 'Your XSH balance is empty. (Hint: use `!deposit`)')
})
}
if (content[0] === '!withdraw') {
if (content.length >= 3) {
var amount = Number(content[1])
var address = Message.content.split(/\s+/)[2]
if (amount === undefined || isNaN(amount)) {
SendMsg(Message, 'Please use `!withdraw <amount> <address>`')
return
}
if (amount <= 1) {
SendMsg(Message, 'Please withdraw higher than 1 XSH')
return
}
WithdrawBalance(Message.author.id, address, amount).then(x => {
SendMsg(Message, '<@' + String(Message.author.id) + '>, You successfully withdrew ' + String(x))
}).catch(x => {
SendMsg(Message, 'Failed to withdraw funds.')
console.log(x)
})
} else {
SendMsg(Message, 'Please use `!withdraw <amount> <address>`')
}
}
if (content[0] === '!hashprofit') {
if (content.length >= 3) {
var amount = Number(content[1])
var algo = String(content[2]).toLowerCase()
if (amount === undefined || isNaN(amount)) {
SendMsg(Message, 'Please use `!hashprofit <hashrate in MH/s> <algo>`')
return
}
if (algos.indexOf(algo) < 0) {
SendMsg(Message, '**Unrecognised algo.** Please choose one of the following:\n' +
'`scrypt, myrgr, lyra2v2, blake2s, x17`')
return
}
request({
url: 'https://blockstats.pw/shield/api/',
json: true
}, function (error, response, body) {
if (error) {
console.log(error)
SendMsg(Message, 'Internal Server error')
return
}
var XSHph = (1000000 * amount * 250 * 3600) / (body['diff_24h'][algo] * 4294967296) // current block reward
var jsons = jsonf[0]
var pXSH = jsons['price_usd']
SendMsg(Message, '(estimated) Hourly: ' + String((XSHph).toFixed(2)) + ' XSH ($' + String((XSHph * pXSH).toFixed(2)) + ') || Daily:' +
String((XSHph * 24).toFixed(2)) + ' XSH ($' + String((XSHph * pXSH * 24).toFixed(2)) + ')')
})
} else {
SendMsg(Message, 'Please use `!hashprofit <hashrate in MH/s> <algo>`')
}
}
if (content[0] === '!tip') {
if (content.length >= 3) {
// var factor = mention.length;
var amount = Number(content[2])
if (mention.length < 1) {
SendMsg(Message, 'Make sure to mention the user you want to !tip (hint: use @username)')
return
}
var totip = mention[0].id
if (totip === Message.author.id) {
SendMsg(Message, 'Stahp it Mikanoshi')
return
}
if (amount === undefined || isNaN(amount)) {
SendMsg(Message, 'Please use `!tip <Person> <amount>`')
return
}
if (amount <= 0.001) {
SendMsg(Message, 'Smart ass >_>')
return
}
GetBalance(Message.author.id).then(balance => {
GetBalance(totip).then(Mainbalance => {
if (balance < amount) {
SendMsg(Message, 'not enough balance')
return
}
UpdateBalance(Message.author.id, balance - amount)
UpdateBalance(totip, Mainbalance + amount)
SendMsg(Message, '<@' + String(Message.author.id) + '> has tipped <@' + String(totip) + '> ' + amount.toFixed(3) + 'XSH')
}).catch(x => {
SendMsg(Message, '<@' + String(totip) + "> doesn't have a address yet, let them use !deposit first")
})
}).catch(x => {
SendMsg(Message, '<@' + String(Message.author.id) + '> Your XSH balance is empty. (Hint: use `!deposit`)')
})
} else {
SendMsg(Message, 'Please use `!tip <User> <amount>`')
}
}
if (content[0] === '!help') {
SendMsg(Message, '`!info` View current XSH trading statistics.\n' +
'`!deposit` Receive your unique XSH deposit address.\n' +
'`!balance` View your current XSH balance.\n' +
'`!withdraw <amount> <address>` Withdraw an amount of your XSH to another XSH address (-0.05 network fee).\n' +
'`!donate <amount>` Donates an amount of XSH to the team.\n' +
'`!chance [amount]` Try your luck! You can win or lose your amount of XSH.\n' +
'`!hashprofit <hashrate in MH/s> <algo>` Estimate earnings for a given hashrate on one of XSH\'s algos.\n' +
'`!tip <User> <amount>` Will tip a person a amount of xsh')
}
})
Client.login('TOKEN')
process.on('uncaughtException', function (err) {
console.error((new Date()).toUTCString() + ' uncaughtException:', err.message)
console.error(err.stack)
process.exit(1)
})