-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcroupier.ts
More file actions
708 lines (579 loc) · 20.5 KB
/
Copy pathcroupier.ts
File metadata and controls
708 lines (579 loc) · 20.5 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
import axios, { AxiosPromise, AxiosRequestConfig } from "axios";
import * as fs from "fs";
import * as _ from "lodash";
import * as moment from "moment";
import * as mongodb from "mongodb";
import * as os from "os";
import * as throttledQueue from "throttled-queue";
import * as Bot from "./keybase-bot";
import Snipe from "./snipe";
import { ChatChannel, MessageSummary, Transaction } from "./keybase-bot";
import { IBetData, IBetList, ICroupierBotConfig, ICroupierDbConfig, IParticipant,
IPopularityContest, IPositionSize, IPowerup, IPowerupAward,
IReactionContent } from "./types";
class Croupier {
public activeSnipes: object;
public bot1: Bot;
public bot2: Bot;
public botUsername: string;
public paperKey1: string;
public paperKey2: string;
public respondedToDM: Set<string>;
// Keeps track of all the channels that have had a Snipe running while the bot was running
// i.e., whom to notify when the bot goes for shutdown or restarts
public channelSet: Set<ChatChannel>;
// Probably should be abstracted into another class
// That would let us, e.g., replace mongodb with postgres more conveniently
private mongoDbUri: string;
private mongoDbUsername: string;
private mongoDbPassword: string;
private mongoDbHost: string;
private mongoDbClient: mongodb.MongoClient;
private mongoDbDatabaseName: string;
private mongoDbDatabase: mongodb.Db;
private mongoDbIsCluster: boolean;
public constructor(botConfig: ICroupierBotConfig, dbConfig: ICroupierDbConfig) {
Object.assign(this, botConfig);
Object.assign(this, dbConfig);
this.bot1 = new Bot(os.homedir());
this.bot2 = new Bot(os.homedir());
this.channelSet = new Set();
this.respondedToDM = new Set();
}
public async init(): Promise<any> {
this.activeSnipes = {};
await this.bot1.init(this.botUsername, this.paperKey1, null);
// Second bot is to read exploding messages
await this.bot2.initFromRunningService();
console.log("both bots initialized");
await this.connectToDatabase();
console.log("connected to database");
}
public async run(loadActiveSnipes: boolean): Promise<any> {
const self: Croupier = this;
if (!this.bot1._service.initialized) {
await this.init();
}
if (loadActiveSnipes) {
this.activeSnipes = await this.loadActiveSnipes();
console.log("1) loaded activeSnipes");
console.log("2) ", this.activeSnipes);
try {
console.log("?");
Object.keys(this.activeSnipes).forEach((stringifiedChannel: string) => {
self.channelSet.add(stringifiedChannel);
});
console.log("x");
console.log("channelSet", self.channelSet);
self.channelSet.forEach((stringifiedChannel: ChatChannel) => {
const ch: ChatChannel = JSON.parse(stringifiedChannel);
self.bot1.chat.send(ch, {
body: "Croupier was just restarted",
}, undefined);
console.log("Sent to channel", ch);
});
} catch (e3) {
console.log("e3", e3);
}
console.log("active snipes loaded");
}
return this.bot2.chat.watchAllChannelsForNewMessages(
this.routeIncomingMessage.bind(this), (e) => console.error(e), {
hideExploding: false,
});
}
public pathToRules(): string {
return `https://github.com/codeforcash/croupier/blob/master/RULES.md`;
}
public copyRulesToKeybase(): Promise<any> {
const destination: string = this.pathToRules();
return new Promise((resolve) => {
fs.copyFile("RULES.md", destination, (err) => {
if (err) {
console.log(err);
return;
}
resolve();
});
});
}
public async shutdown(): Promise<any> {
const self: Croupier = this;
self.channelSet.forEach(async (stringifiedChannel: string) => {
const channel: ChatChannel = JSON.parse(stringifiedChannel);
try {
await self.bot1.chat.send(channel, {
body: "Bot is going for immediate shutdown",
}, undefined);
if (self.activeSnipes[channel]) {
const snipe: Snipe = self.activeSnipes[channel];
clearTimeout(snipe.timeout);
snipe.runClock = () => {
// empty
};
}
} catch (e) {
// empty
}
});
this.activeSnipes = {};
await this.bot1.deinit();
await this.bot2.deinit();
}
public async checkWalletBalance(username: string): Promise<any> {
const self: Croupier = this;
console.log("checking wallet balance");
return new Promise(async (resolve) => {
console.log("inside promise");
self.bot1.wallet
.lookup(username)
.then((acct) => {
axios
.get(`https://horizon.stellar.org/accounts/${acct.accountId}`)
.then((res) => {
let balance: number = 0;
res.data.balances.forEach((eachAcct) => {
balance += eachAcct.balance;
});
resolve(balance);
})
.catch((e) => {
console.log("e2 error");
resolve(0);
});
})
.catch((e) => {
console.log("...error");
resolve(0);
});
});
}
public tabulateNetGains(winnerUsername: string, winnerTotal: number,
participants: Array<IParticipant>): Promise<number> {
const self: Croupier = this;
const netGains: object = {};
for (const participant of participants) {
if (typeof netGains[participant.username] === "undefined") {
netGains[participant.username] = 0;
}
netGains[participant.username] -= participant.transaction.amount;
}
// Possible the winner was a free participant, someone contributed on their behalf, etc.
if (typeof netGains[winnerUsername] === "undefined") {
netGains[winnerUsername] = 0;
}
netGains[winnerUsername] += winnerTotal;
console.log("netGains", netGains);
return new Promise((resolve) => {
const collection: mongodb.Collection = self.mongoDbDatabase.collection("netGains");
collection.updateOne({}, { $inc: netGains }, (err, res) => {
if (err) {
console.log("updateOne err", err);
throw err;
}
const projection: object = {};
projection[winnerUsername] = 1;
collection.findOne({}, projection).then((doc, err2) => {
if (err2 || !doc) {
console.log("findOne err", err2);
throw err2;
}
console.log("findOne doc", doc);
resolve(doc[winnerUsername]);
});
});
});
}
public documentSnipe(snipe: Snipe, reason: string): void {
const self: Croupier = this;
let wasCancelled: number;
let winner: string;
let cancellationReason: string;
if (reason === "lack-of-participants" || reason === "flip-error") {
wasCancelled = 1;
winner = null;
cancellationReason = reason;
} else {
wasCancelled = 0;
winner = reason;
cancellationReason = null;
}
const myquery: object = { _id: mongodb.ObjectID(snipe.snipeId) };
const newvalues: object = {
$set: {
cancellation_reason: cancellationReason,
in_progress: 0,
updatedAt: +new Date(),
was_cancelled: wasCancelled,
winner,
},
};
const snipesCollection: mongodb.Collection = self.mongoDbDatabase.collection("snipes");
snipesCollection.updateOne(myquery, newvalues, (err2, res) => {
if (err2) {
throw err2;
}
});
}
public async processRefund(txn: Transaction, channel: ChatChannel): Promise<any> {
console.log("well we did call processRefund");
const self: Croupier = this;
const snipe: Snipe = this.activeSnipes[JSON.stringify(channel)];
let refund: number;
console.log("refunding txn");
return new Promise((resolve) => {
console.log("inside refund promise");
setTimeout(() => {
console.log("inside refund timeout - at least 5s should have passed");
this.calculateTransactionFees(txn)
.then((transactionFees) => {
console.log("not refunding txn fees", transactionFees);
refund = _.round(txn.amount - transactionFees, 7);
console.log("total refund is", refund);
snipe.moneySend(refund, txn.fromUsername).then(() => {
resolve();
}).catch((e) => {
console.log("there was an error with the refund", e);
self.bot1.chat.send(
{
name: `zackburt,${self.botUsername}`,
public: false,
topicType: "chat",
},
{
body: `There was an error processing a refund
Snipe: ${snipe.snipeId}
Channel topic: ${channel.topicName}
Channel name: ${channel.name}
Amount: ${refund.toString()}
Recipient: ${txn.fromUsername}
Initial Txn Id: ${txn.txId}
ERRORS: ${e}`,
},
undefined,
);
});
});
}, self.MillisecondsToWaitForTransactionToSettle(txn));
});
}
public MillisecondsToWaitForTransactionToSettle(txn: Transaction): number {
const now: number = +new Date();
const millisecondsElapsed: number = (now - txn.time);
let timeToWait: number;
if (millisecondsElapsed > 5000) {
timeToWait = 0;
} else {
timeToWait = 5000 - millisecondsElapsed;
}
console.log("time to Wait before calculating transaction fees", timeToWait);
return timeToWait;
}
public calculateTransactionFees(txn: Transaction): Promise<number> {
const self: Croupier = this;
return new Promise((resolve) => {
// Temporary hack to always return 0.00001 for fees.
resolve(0.00001);
return;
setTimeout(() => {
self.bot1.wallet.details(txn.txId).then((details) => {
const xlmFeeMatch: Array<any> = details.feeChargedDescription.match(/(\d\.\d+) XLM/);
if (xlmFeeMatch !== null) {
const fee: number = parseFloat(xlmFeeMatch[1]);
console.log("fee", fee);
resolve(fee);
}
}).catch((e) => {
console.log(e);
resolve(0.00001);
});
}, self.MillisecondsToWaitForTransactionToSettle(txn));
});
}
public deleteSnipeLog(channel: ChatChannel): void {
const self: Croupier = this;
const snipe: Snipe = this.activeSnipes[JSON.stringify(channel)];
const myquery: object = { _id: mongodb.ObjectID(snipe.snipeId) };
const snipesCollection: mongodb.Collection = self.mongoDbDatabase.collection("snipes");
snipesCollection.deleteOne(myquery, (err, res) => {
if (err) {
throw err;
}
});
}
public updateSnipeLog(channel: ChatChannel): void {
const self: Croupier = this;
const snipe: Snipe = this.activeSnipes[JSON.stringify(channel)];
const participants: string = JSON.stringify(snipe.participants);
const positionSizes: string = JSON.stringify(snipe.positionSizes);
const blinds: number = snipe.blinds;
const snipeId: string = snipe.snipeId;
const myquery: object = { _id: mongodb.ObjectID(snipe.snipeId) };
console.log("myQuery", myquery);
const newvalues: object = {
$set: {
blinds,
clockRemaining: snipe.getTimeLeft(),
participants,
position_sizes: positionSizes,
potSize: snipe.calculatePotSize(),
updatedAt: +new Date(),
},
};
const snipesCollection: mongodb.Collection = self.mongoDbDatabase.collection("snipes");
snipesCollection.updateOne(myquery, newvalues, (err, res) => {
if (err) {
throw err;
}
});
}
private connectToDatabase(): Promise<any> {
const self: Croupier = this;
if (process.env.TEST) {
this.mongoDbDatabaseName = "testcroupier";
} else if (process.env.DEVELOPMENT) {
this.mongoDbDatabaseName = "devcroupier";
} else {
this.mongoDbDatabaseName = "croupier";
}
console.log("Talking to db: ", this.mongoDbDatabaseName);
let uri: string;
if (this.mongoDbIsCluster) {
uri = "mongodb+srv://";
} else {
uri = "mongodb://";
}
uri += `${this.mongoDbUsername}:${this.mongoDbPassword}@${this.mongoDbHost}`;
uri += `/${this.mongoDbDatabaseName}?retryWrites=true&w=majority`;
this.mongoDbUri = uri;
console.log(uri);
self.mongoDbClient = new mongodb.MongoClient(this.mongoDbUri, {
reconnectInterval: 1000,
reconnectTries: Number.MAX_VALUE,
useNewUrlParser: true,
});
return new Promise(async (resolve) => {
try {
await self.mongoDbClient.connect();
self.mongoDbDatabase = self.mongoDbClient.db(self.mongoDbDatabaseName);
} catch (err) {
console.log("we were unable to connect to mongodb");
throw err;
}
resolve();
});
}
private logNewSnipe(snipe: Snipe): Promise<any> {
const self: Croupier = this;
return new Promise((resolve, reject) => {
const snipesCollection: mongodb.Collection = self.mongoDbDatabase.collection("snipes");
snipesCollection.insertOne(
{
bettingStarted: snipe.bettingStarted,
channel: snipe.channel,
countdown: snipe.countdown,
in_progress: 1,
},
(err, res) => {
if (err) {
console.log(err);
throw err;
}
resolve(res.insertedId.toString());
},
);
});
}
private extractTxn(msg: MessageSummary): void {
const txnId: string = msg.content.text.payments[0].result.sent;
this.bot1.wallet.details(txnId).then((details) => this.processTxn(details, msg));
}
private processTxn(txn: Transaction, msg: MessageSummary): void {
const channel: ChatChannel = msg.channel;
const snipe: Snipe = this.activeSnipes[JSON.stringify(channel)];
// If the transaction was not sent to us, then ignore
if (txn.toUsername !== this.botUsername) {
return;
}
// If they aren't sending XLM but instead some other unexpected asset, then ignore
const isNative: boolean = txn.asset.type === "native";
if (!isNative) {
return;
}
if (parseFloat(txn.amount) < 0.01) {
this.bot1.chat.send(
channel,
{
body: `Thanks for the tip, but bets should be >= 0.01XLM`,
},
undefined,
);
return;
}
if (typeof snipe === "undefined") {
this.startNewSnipe(msg, txn);
} else {
const currentPotSize: number = snipe.calculatePotSize();
const thisBetSize: number = txn.amount;
if (currentPotSize + thisBetSize >= 20000) {
snipe.chatSend(`In order to make Croupier available within as many international territories as possible,
pot sizes are limited to 20,000 XLM`);
this.processRefund(txn, channel);
return;
}
if (snipe.bettingOpen === false) {
snipe.chatSend(`Betting has closed - refunding`);
// Ensure the transaction is Completed before refunding
this.processRefund(txn, channel);
return;
}
snipe.processNewBet(txn, msg).then((betProcessed) => {
if (betProcessed) {
snipe.resetSnipeClock();
}
});
}
}
private startNewSnipe(msg: MessageSummary, txn: Transaction): void {
const self: Croupier = this;
const channel: ChatChannel = msg.channel;
let countdown: number = 60;
const countdownMatch: Array<any> = msg.content.text.body.match(/countdown:\s?(\d+)/i);
if (countdownMatch !== null) {
countdown = parseInt(countdownMatch[1], 10);
if (countdown < 5 || countdown > 60 * 60 * 24 * 7) {
countdown = 60;
this.bot1.chat.send(
channel,
{
body: `Bad value of countdown. Must be >= 5 (5 seconds) && <= 604800 (7 days)`,
},
undefined,
);
}
}
const chatThrottle: any = throttledQueue(5, 5000);
const moneyThrottle: any = throttledQueue(1, 1000);
this.activeSnipes[JSON.stringify(channel)] = new Snipe(this, channel,
{ bot1: this.bot1, bot2: this.bot2 }, { countdown });
const snipe: Snipe = this.activeSnipes[JSON.stringify(channel)];
this.logNewSnipe(snipe).then((snipeId) => {
snipe.snipeId = snipeId;
snipe.launchSnipe();
snipe.processNewBet(txn, msg);
});
}
private respondToDM(msg: MessageSummary): void {
// Respond to DMs once per round
if (this.respondedToDM.has(msg.sender.username)) {
return;
}
this.respondedToDM.add(msg.sender.username);
const channel: ChatChannel = msg.channel;
const helpMsg: string = `These messages are not monitored.
Have some feedback? Message @zackburt here on Keybase.
Filing a bug report or feature request? Post on GitHub: https://github.com/codeforcash/croupier/issues/
Want to read the rules or start a game? /keybase/public/${this.botUsername}/RULES.md`;
this.bot1.chat.send(channel, {
body: helpMsg,
});
}
private routeIncomingMessage(msg: MessageSummary): void {
const self: Croupier = this;
try {
console.log(msg);
let snipe: Snipe = this.activeSnipes[JSON.stringify(msg.channel)];
if (msg.channel.membersType === "impteamnative") {
if (msg.channel.name.match(/,/g).length === 1) {
this.respondToDM(msg);
return;
}
}
if (typeof snipe !== "undefined" && snipe.freeze
&& msg.sender.username !== snipe.freeze
&& msg.sender.username !== self.botUsername) {
snipe.freezeBet(msg);
return;
}
if (msg.content.type === "text" && msg.content.text.payments && msg.content.text.payments.length === 1) {
this.extractTxn(msg);
}
if (typeof snipe === "undefined") {
// Check whether we're in a subteam of an active snipe
// Potential source of application slowdown?
Object.keys(this.activeSnipes).forEach((stringifiedChannel: string) => {
const potentialSnipe: Snipe = this.activeSnipes[stringifiedChannel];
if (potentialSnipe && msg.channel.name === potentialSnipe.subteamName()) {
snipe = potentialSnipe;
}
});
if (typeof(snipe) === "undefined") {
return;
}
}
if (msg.content.type === "flip" && msg.sender.username === this.botUsername) {
snipe.monitorFlipResults(msg);
return;
}
if (msg.content.type === "text" && msg.content.text.body) {
snipe.checkTextForPowerup(msg);
snipe.scrollCount += 1;
}
if (msg.content.type === "reaction") {
snipe.checkForPopularityContestVote(msg);
snipe.checkReactionForPowerup(msg);
snipe.checkForFreeEntry(msg);
snipe.checkForJoiningRoom(msg);
}
if (msg.content.type === "delete") {
snipe.checkForPopularityContestVoteRemoval(msg);
}
} catch (err) {
console.error(err);
}
}
private loadActiveSnipes(): object {
const self: Croupier = this;
return new Promise((resolve) => {
const snipes: object = {};
const myquery: object = { in_progress: 1, blinds: { $exists: true } };
const snipesCollection: mongodb.Collection = self.mongoDbDatabase.collection("snipes");
snipesCollection.find(myquery).toArray((err, results) => {
if (err) {
throw err;
}
console.log(results);
results.forEach((result) => {
const channel: ChatChannel = result.channel;
snipes[JSON.stringify(channel)] = new Snipe(
self,
channel,
{
bot1: self.bot1,
bot2: self.bot2,
},
{
bettingStarted: parseInt(result.bettingStarted, 10),
blinds: parseFloat(result.blinds),
clockRemaining: result.clockRemaining,
countdown: result.countdown,
participants: JSON.parse(result.participants),
position_sizes: JSON.parse(result.position_sizes),
potSize: parseInt(result.potSize, 10),
snipeId: result._id.toString(),
},
);
});
Object.keys(snipes).forEach((chid) => {
const snipeChannel: ChatChannel = JSON.parse(chid);
const snipe: Snipe = snipes[chid];
snipes[chid].chatSend("Previous bets are still valid!");
snipes[chid].chatSend(snipe.buildBettingTable());
snipe.launchSnipe();
});
resolve(snipes);
});
});
}
}
export default Croupier;