-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompetitive-bot.js
More file actions
704 lines (572 loc) Β· 33.2 KB
/
Copy pathcompetitive-bot.js
File metadata and controls
704 lines (572 loc) Β· 33.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
require('dotenv').config();
const { ethers } = require('ethers');
const axios = require('axios');
// Configuration for maximum competitiveness
const CONFIG = {
PRIVATE_KEY: process.env.BOT_PRIVATE_KEY || '',
// Ultra-fast RPC endpoints
RPC_URLS: [
'https://rpc.ankr.com/arbitrum',
'https://1rpc.io/arb',
'https://arb1.arbitrum.io/rpc'
],
// Contract addresses
ORACLE_ADDRESS: '0xa935db8cb0f45256e3df77cbff1980cf7aeffbe4',
BEACON_ADDRESS: '0x0d623183d4a0de6e4871dfdd1350312c3b1538b6',
// ULTRA AGGRESSIVE - BEAT THE 0.22 SECOND GAP!
GAS_MULTIPLIER: 250, // 150% higher gas for MAXIMUM priority
MIN_PROFIT_WEI: ethers.utils.parseEther('0.000001'), // Accept ANY profit
REVERSION_CHECK_INTERVAL: 250, // Check every 0.25 seconds - LIGHTNING FAST
EVENT_SCAN_BLOCKS: 50, // Look back for recent events
SETTLEMENT_BUFFER_MS: 0, // ZERO buffer - settle IMMEDIATELY when eligible
// MEV protection
USE_FLASHLOAN_SETTLEMENT: false,
BUNDLE_TRANSACTIONS: false,
DISCORD_WEBHOOK: process.env.DISCORD_WEBHOOK || ''
};
// Enhanced Oracle ABI with events
const ORACLE_ABI = [
// Read functions
"function nextReportId() view returns (uint256)",
"function reportMeta(uint256) view returns (tuple(address token1, address token2, uint256 feePercentage, uint256 multiplier, uint256 settlementTime, uint256 exactToken1Report, uint256 fee, uint256 escalationHalt, uint256 disputeDelay, uint256 protocolFee, uint256 settlerReward, uint256 requestBlock, bool timeType))",
"function reportStatus(uint256) view returns (tuple(uint256 currentAmount1, uint256 currentAmount2, address currentReporter, address initialReporter, uint256 reportTimestamp, uint256 settlementTimestamp, uint256 price, uint256 lastDisputeBlock, bool isSettled, bool disputeOccurred, bool isDistributed, uint256 initialReportTimestamp, uint256 lastReportTrueTime))",
"function extraData(uint256) view returns (address creator, uint256 requestTrueTime, address callbackContract, bytes4 callbackSelector, bool trackDisputes, uint256 numReports, uint256 callbackGasLimit, bool keepFee)",
"function settle(uint256) returns (uint256 price, uint256 settlementTimestamp)",
// Events for real-time tracking
"event ReportInstanceCreated(uint256 indexed reportId, address indexed token1Address, address indexed token2Address, uint256 feePercentage, uint256 multiplier, uint256 exactToken1Report, uint256 ethFee, address creator, uint256 settlementTime, uint256 escalationHalt, uint256 disputeDelay, uint256 protocolFee, uint256 settlerReward, bool timeType, address callbackContract, bytes4 callbackSelector, bool trackDisputes, uint256 callbackGasLimit, bool keepFee)",
"event InitialReportSubmitted(uint256 indexed reportId, address reporter, uint256 amount1, uint256 amount2, address indexed token1Address, address indexed token2Address, uint256 swapFee, uint256 protocolFee, uint256 settlementTime, uint256 disputeDelay, uint256 escalationHalt, bool timeType, address callbackContract, bytes4 callbackSelector, bool trackDisputes, uint256 callbackGasLimit)",
"event ReportDisputed(uint256 indexed reportId, address disputer, uint256 newAmount1, uint256 newAmount2, address indexed token1Address, address indexed token2Address, uint256 swapFee, uint256 protocolFee, uint256 settlementTime, uint256 disputeDelay, uint256 escalationHalt, bool timeType, address callbackContract, bytes4 callbackSelector, bool trackDisputes, uint256 callbackGasLimit)",
"event ReportSettled(uint256 indexed reportId, uint256 price, uint256 settlementTimestamp)"
];
const BEACON_ABI = [
"function freeMoneyLight() external",
"function freeMoney() external",
"function freeMoneyMedium() external"
];
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m'
};
class CompetitiveBot {
constructor() {
this.rpcIndex = 0;
this.provider = null;
this.wallet = null;
this.oracle = null;
this.beacon = null;
// Tracking
this.activeReports = new Map(); // reportId -> settlement info
this.scheduledSettlements = new Map(); // reportId -> timeout
this.processedReports = new Set();
// Performance with precise profit tracking
this.metrics = {
settlements: 0,
reversionChecks: 0,
eventsCaught: 0,
totalProfit: ethers.BigNumber.from(0),
gasSpent: ethers.BigNumber.from(0),
startTime: Date.now(),
settlementAttempts: 0,
failedAttempts: 0,
startingBalance: null,
allProfits: [] // Track every single profit
};
}
async initialize() {
console.log(`${colors.bright}${colors.cyan}π COMPETITIVE SETTLEMENT BOT STARTING${colors.reset}\n`);
// Connect to fastest RPC
await this.connectToFastestRPC();
// Setup contracts
this.wallet = new ethers.Wallet(CONFIG.PRIVATE_KEY, this.provider);
this.oracle = new ethers.Contract(CONFIG.ORACLE_ADDRESS, ORACLE_ABI, this.wallet);
this.beacon = new ethers.Contract(CONFIG.BEACON_ADDRESS, BEACON_ABI, this.wallet);
console.log(`${colors.green}β
Wallet: ${this.wallet.address}${colors.reset}`);
const balance = await this.wallet.getBalance();
console.log(`${colors.green}β
Balance: ${ethers.utils.formatEther(balance)} ETH${colors.reset}`);
// Store starting balance for profit calculation
this.metrics.startingBalance = balance;
if (balance.lt(ethers.utils.parseEther('0.001'))) {
console.log(`${colors.red}β οΈ WARNING: Low balance!${colors.reset}`);
}
// Setup event listeners
this.setupEventListeners();
// Start background tasks
this.startReversionChecker();
this.startBeaconSpammer();
this.startPreemptiveChecker(); // NEW: Check slightly before deadline
console.log(`${colors.bright}${colors.green}π― BOT READY - HUNTING FOR SETTLEMENTS${colors.reset}\n`);
}
async connectToFastestRPC() {
const promises = CONFIG.RPC_URLS.map(async (rpc, index) => {
try {
const provider = new ethers.providers.JsonRpcProvider({
url: rpc,
timeout: 5000
});
const start = Date.now();
await provider.getBlockNumber();
const latency = Date.now() - start;
return { provider, latency, index, rpc };
} catch (e) {
return null;
}
});
const results = (await Promise.all(promises)).filter(Boolean);
if (results.length === 0) {
throw new Error('No working RPCs found');
}
// Use fastest RPC
results.sort((a, b) => a.latency - b.latency);
const fastest = results[0];
this.provider = fastest.provider;
console.log(`${colors.green}β‘ Using fastest RPC: ${fastest.rpc.split('/')[2]} (${fastest.latency}ms)${colors.reset}`);
}
setupEventListeners() {
console.log(`${colors.blue}π‘ Setting up event listeners...${colors.reset}`);
// Listen for new reports
this.oracle.on('ReportInstanceCreated', (reportId, token1, token2, ...args) => {
this.handleNewReport(reportId, args);
});
// Listen for report submissions
this.oracle.on('InitialReportSubmitted', (reportId, reporter, ...args) => {
this.handleReportSubmitted(reportId, args);
});
// Listen for disputes (reset timing)
this.oracle.on('ReportDisputed', (reportId, disputer, ...args) => {
this.handleReportDisputed(reportId);
});
// Listen for settlements (remove from tracking)
this.oracle.on('ReportSettled', (reportId, price, timestamp) => {
this.handleReportSettled(reportId);
});
console.log(`${colors.green}β
Event listeners active${colors.reset}`);
}
async handleNewReport(reportId, args) {
const reportIdStr = reportId.toString();
this.metrics.eventsCaught++;
console.log(`${colors.cyan}π NEW REPORT CREATED: #${reportIdStr}${colors.reset}`);
// Extract data from event
const [feePercentage, multiplier, exactToken1Report, ethFee, creator, settlementTime, escalationHalt, disputeDelay, protocolFee, settlerReward, timeType, callbackContract] = args;
// Skip if has callback
if (callbackContract !== ethers.constants.AddressZero) {
console.log(`${colors.yellow}β οΈ Report #${reportIdStr} has callback - SKIPPING${colors.reset}`);
return;
}
// Store for tracking
this.activeReports.set(reportIdStr, {
reportId: reportIdStr,
settlerReward,
settlementTime: settlementTime.toNumber(),
timeType,
created: Date.now(),
status: 'created'
});
console.log(`${colors.green}π Tracking report #${reportIdStr} - Reward: ${ethers.utils.formatEther(settlerReward)} ETH${colors.reset}`);
}
async handleReportSubmitted(reportId, args) {
const reportIdStr = reportId.toString();
const report = this.activeReports.get(reportIdStr);
if (!report) return;
console.log(`${colors.blue}π REPORT SUBMITTED: #${reportIdStr}${colors.reset}`);
// Update status
report.status = 'submitted';
report.submitted = Date.now();
// Schedule settlement attempt
await this.scheduleSettlement(reportIdStr, report);
}
async scheduleSettlement(reportIdStr, report) {
const currentTime = Math.floor(Date.now() / 1000);
const currentBlock = await this.provider.getBlockNumber();
// Get actual report data
const [meta, status] = await Promise.all([
this.oracle.reportMeta(reportIdStr),
this.oracle.reportStatus(reportIdStr)
]);
const reportTime = status.reportTimestamp.toNumber();
const deadline = reportTime + report.settlementTime;
const checkTime = report.timeType ? currentTime : currentBlock;
let waitTime;
if (report.timeType) {
waitTime = Math.max(0, (deadline - currentTime) * 1000) + CONFIG.SETTLEMENT_BUFFER_MS;
} else {
// For block-based, estimate time (3.5s per block for speed - beat the 0.22s gap!)
const blocksToWait = Math.max(0, deadline - currentBlock);
waitTime = blocksToWait * 3500 + CONFIG.SETTLEMENT_BUFFER_MS; // Faster timing estimate
}
console.log(`${colors.yellow}β° Scheduling settlement #${reportIdStr} in ${Math.round(waitTime/1000)}s${colors.reset}`);
// Clear any existing timeout
if (this.scheduledSettlements.has(reportIdStr)) {
clearTimeout(this.scheduledSettlements.get(reportIdStr));
}
// Schedule the settlement attempt
const timeout = setTimeout(async () => {
await this.attemptSettlement(reportIdStr);
}, waitTime);
this.scheduledSettlements.set(reportIdStr, timeout);
}
async attemptSettlement(reportIdStr) {
if (this.processedReports.has(reportIdStr)) return;
this.metrics.settlementAttempts++;
console.log(`${colors.bright}${colors.green}π― ATTEMPTING SETTLEMENT #${reportIdStr} (Attempt #${this.metrics.settlementAttempts})${colors.reset}`);
const balanceBefore = await this.wallet.getBalance();
try {
// Ultra-fast profitability check
const [meta, gasPrice] = await Promise.all([
this.oracle.reportMeta(reportIdStr),
this.provider.getGasPrice()
]);
const priorityGasPrice = gasPrice.mul(CONFIG.GAS_MULTIPLIER).div(100);
// Estimate gas with immediate execution if profitable
let estimatedGas;
try {
estimatedGas = await this.oracle.estimateGas.settle(reportIdStr);
} catch (e) {
console.log(`${colors.red}β Settlement #${reportIdStr} would revert: ${e.reason || e.message.substring(0, 50)}${colors.reset}`);
this.processedReports.add(reportIdStr);
this.metrics.failedAttempts++;
return;
}
const gasCost = priorityGasPrice.mul(estimatedGas);
const expectedProfit = meta.settlerReward.sub(gasCost);
// Show expected profit even if tiny
const expectedProfitETH = ethers.utils.formatEther(expectedProfit);
console.log(`${colors.cyan}π° Expected profit: ${expectedProfitETH} ETH${colors.reset}`);
if (expectedProfit.lt(CONFIG.MIN_PROFIT_WEI)) {
console.log(`${colors.yellow}πΈ Settlement #${reportIdStr} below threshold: ${expectedProfitETH} ETH${colors.reset}`);
this.processedReports.add(reportIdStr);
this.metrics.failedAttempts++;
return;
}
// MAXIMUM SPEED EXECUTION - BEAT THAT 0.22 SECOND GAP!
const tx = await this.oracle.settle(reportIdStr, {
gasPrice: priorityGasPrice,
gasLimit: estimatedGas.mul(105).div(100), // Minimal buffer for max speed
type: 2, // EIP-1559 for fastest inclusion
maxFeePerGas: priorityGasPrice,
maxPriorityFeePerGas: priorityGasPrice.div(4) // MASSIVE priority fee for instant inclusion
});
console.log(`${colors.bright}${colors.green}π TX SENT: ${tx.hash} (Gas: ${ethers.utils.formatUnits(priorityGasPrice, 'gwei')} gwei)${colors.reset}`);
this.processedReports.add(reportIdStr);
// IMMEDIATELY update basic metrics
this.metrics.settlements++;
const estimatedProfit = meta.settlerReward.sub(priorityGasPrice.mul(estimatedGas));
this.metrics.totalProfit = this.metrics.totalProfit.add(estimatedProfit);
console.log(`${colors.bright}${colors.green}π° SETTLEMENT TX SENT #${reportIdStr}! (Settlement #${this.metrics.settlements})${colors.reset}`);
console.log(` Estimated Profit: ${ethers.utils.formatEther(estimatedProfit)} ETH`);
console.log(` TX Hash: ${tx.hash}`);
console.log(` Total Settlements So Far: ${this.metrics.settlements}`);
// Store preliminary profit data
const preliminaryProfit = {
reportId: reportIdStr,
calculatedProfit: estimatedProfit,
realProfit: ethers.BigNumber.from(0), // Will update when confirmed
timestamp: Date.now(),
block: 0, // Will update when confirmed
gasUsed: estimatedGas,
txHash: tx.hash,
confirmed: false
};
this.metrics.allProfits.push(preliminaryProfit);
// Update when confirmed (non-blocking)
tx.wait().then(async (receipt) => {
const balanceAfter = await this.wallet.getBalance();
const actualGasCost = receipt.gasUsed.mul(receipt.effectiveGasPrice);
const calculatedProfit = meta.settlerReward.sub(actualGasCost);
const realProfit = balanceAfter.sub(balanceBefore);
// Update the stored profit data
const profitIndex = this.metrics.allProfits.length - 1;
if (this.metrics.allProfits[profitIndex] && this.metrics.allProfits[profitIndex].txHash === tx.hash) {
this.metrics.allProfits[profitIndex].calculatedProfit = calculatedProfit;
this.metrics.allProfits[profitIndex].realProfit = realProfit;
this.metrics.allProfits[profitIndex].block = receipt.blockNumber;
this.metrics.allProfits[profitIndex].gasUsed = receipt.gasUsed;
this.metrics.allProfits[profitIndex].confirmed = true;
}
// Update total profit with actual values
this.metrics.totalProfit = this.metrics.totalProfit.sub(estimatedProfit).add(calculatedProfit);
this.metrics.gasSpent = this.metrics.gasSpent.add(actualGasCost);
const calculatedProfitETH = ethers.utils.formatEther(calculatedProfit);
const realProfitETH = ethers.utils.formatEther(realProfit);
console.log(`${colors.bright}${colors.green}β
SETTLEMENT CONFIRMED #${reportIdStr}!${colors.reset}`);
console.log(` Final Calculated Profit: ${calculatedProfitETH} ETH`);
console.log(` Real Balance Change: ${realProfitETH} ETH`);
console.log(` Gas Used: ${receipt.gasUsed.toString()}`);
console.log(` Block: ${receipt.blockNumber}`);
this.sendAlert(`π° Settlement Confirmed #${this.metrics.settlements}!\nReport #${reportIdStr}\nProfit: ${calculatedProfitETH} ETH\nReal: ${realProfitETH} ETH\nTx: ${tx.hash}\nBlock: ${receipt.blockNumber}`);
}).catch(e => {
console.log(`${colors.red}β Settlement #${reportIdStr} failed in block: ${e.reason || e.message}${colors.reset}`);
this.metrics.failedAttempts++;
this.metrics.settlements--; // Rollback the count
// Remove the failed settlement from profits
const profitIndex = this.metrics.allProfits.length - 1;
if (this.metrics.allProfits[profitIndex] && this.metrics.allProfits[profitIndex].txHash === tx.hash) {
const failedProfit = this.metrics.allProfits.splice(profitIndex, 1)[0];
this.metrics.totalProfit = this.metrics.totalProfit.sub(failedProfit.calculatedProfit);
}
});
} catch (error) {
console.log(`${colors.red}β Failed to attempt settlement #${reportIdStr}: ${error.reason || error.message}${colors.reset}`);
this.metrics.failedAttempts++;
// Don't mark as processed if it's a timing issue - retry
if (!error.message.includes('time') && !error.message.includes('settlement')) {
this.processedReports.add(reportIdStr);
}
}
}
startReversionChecker() {
console.log(`${colors.blue}π Starting reversion checker (${CONFIG.REVERSION_CHECK_INTERVAL}ms intervals)${colors.reset}`);
setInterval(async () => {
this.metrics.reversionChecks++;
// Check active reports that might be ready
for (const [reportIdStr, report] of this.activeReports) {
if (this.processedReports.has(reportIdStr) || report.status !== 'submitted') continue;
try {
// Try to estimate gas - if it doesn't revert, we can settle
const gas = await this.oracle.estimateGas.settle(reportIdStr);
// If we get here, settlement is possible
console.log(`${colors.cyan}β‘ Reversion check found opportunity #${reportIdStr}${colors.reset}`);
await this.attemptSettlement(reportIdStr);
} catch (e) {
// Still reverts, not ready yet
}
}
}, CONFIG.REVERSION_CHECK_INTERVAL);
}
startBeaconSpammer() {
console.log(`${colors.blue}π‘ Starting SmartAutoBeacon spammer${colors.reset}`);
setInterval(async () => {
try {
// Try freeMoneyLight first (fastest)
const balanceBefore = await this.wallet.getBalance();
const gas = await this.beacon.estimateGas.freeMoneyLight();
const gasPrice = await this.provider.getGasPrice();
const priorityGasPrice = gasPrice.mul(110).div(100); // Back to stable beacon gas
const tx = await this.beacon.freeMoneyLight({
gasPrice: priorityGasPrice,
gasLimit: gas.mul(110).div(100)
});
console.log(`${colors.green}π― SmartAutoBeacon TX sent: ${tx.hash}${colors.reset}`);
// Add pending beacon to tracking
this.metrics.allProfits.push({
reportId: 'BEACON',
calculatedProfit: ethers.BigNumber.from(0), // Will update when confirmed
realProfit: ethers.BigNumber.from(0),
timestamp: Date.now(),
block: 0,
gasUsed: gas,
txHash: tx.hash,
confirmed: false
});
tx.wait().then(async (receipt) => {
const balanceAfter = await this.wallet.getBalance();
const profit = balanceAfter.sub(balanceBefore);
const profitETH = ethers.utils.formatEther(profit);
console.log(`${colors.green}π° Beacon confirmed! Profit: ${profitETH} ETH (Block: ${receipt.blockNumber})${colors.reset}`);
// Update the beacon profit in tracking
const beaconIndex = this.metrics.allProfits.findIndex(p => p.txHash === tx.hash);
if (beaconIndex >= 0) {
this.metrics.allProfits[beaconIndex].calculatedProfit = profit;
this.metrics.allProfits[beaconIndex].realProfit = profit;
this.metrics.allProfits[beaconIndex].block = receipt.blockNumber;
this.metrics.allProfits[beaconIndex].gasUsed = receipt.gasUsed;
this.metrics.allProfits[beaconIndex].confirmed = true;
}
if (profit.gt(0)) {
this.metrics.totalProfit = this.metrics.totalProfit.add(profit);
}
}).catch(() => {
// Remove failed beacon from tracking
const beaconIndex = this.metrics.allProfits.findIndex(p => p.txHash === tx.hash);
if (beaconIndex >= 0) {
this.metrics.allProfits.splice(beaconIndex, 1);
}
});
} catch (e) {
// Beacon not profitable, silent fail
}
}, 3000); // Every 3 seconds for more opportunities
}
startPreemptiveChecker() {
console.log(`${colors.blue}β‘ Starting preemptive checker (beats the competition by checking early)${colors.reset}`);
setInterval(async () => {
const currentTime = Math.floor(Date.now() / 1000);
const currentBlock = await this.provider.getBlockNumber();
for (const [reportIdStr, report] of this.activeReports) {
if (this.processedReports.has(reportIdStr) || report.status !== 'submitted') continue;
try {
const status = await this.oracle.reportStatus(reportIdStr);
const meta = await this.oracle.reportMeta(reportIdStr);
const reportTime = status.reportTimestamp.toNumber();
const deadline = reportTime + meta.settlementTime.toNumber();
const checkTime = meta.timeType ? currentTime : currentBlock;
// Check if we're VERY close to deadline (within 1 second/block)
const timeUntilSettlement = deadline - checkTime;
if (timeUntilSettlement <= 1 && timeUntilSettlement >= 0) {
console.log(`${colors.bright}${colors.red}π¨ PREEMPTIVE STRIKE! Report #${reportIdStr} (${timeUntilSettlement} ${meta.timeType ? 'seconds' : 'blocks'} early)${colors.reset}`);
// Try settlement slightly early - might work due to network delays
try {
const gas = await this.oracle.estimateGas.settle(reportIdStr);
console.log(`${colors.green}β‘ EARLY SETTLEMENT POSSIBLE! Executing...${colors.reset}`);
await this.attemptSettlement(reportIdStr);
} catch (e) {
// Still too early, but we're ready
console.log(`${colors.yellow}β³ Almost ready... (${e.message.substring(0, 30)})${colors.reset}`);
}
}
} catch (e) {
// Skip errors
}
}
}, 100); // Check every 100ms for ultra-precise timing
}
handleReportDisputed(reportId) {
const reportIdStr = reportId.toString();
console.log(`${colors.yellow}βοΈ REPORT DISPUTED: #${reportIdStr} - Rescheduling${colors.reset}`);
const report = this.activeReports.get(reportIdStr);
if (report) {
this.scheduleSettlement(reportIdStr, report);
}
}
handleReportSettled(reportId) {
const reportIdStr = reportId.toString();
console.log(`${colors.magenta}β
REPORT SETTLED: #${reportIdStr}${colors.reset}`);
// Clean up
this.activeReports.delete(reportIdStr);
if (this.scheduledSettlements.has(reportIdStr)) {
clearTimeout(this.scheduledSettlements.get(reportIdStr));
this.scheduledSettlements.delete(reportIdStr);
}
}
async sendAlert(message) {
if (!CONFIG.DISCORD_WEBHOOK) return;
try {
await axios.post(CONFIG.DISCORD_WEBHOOK, {
content: message,
username: 'Competitive Bot'
});
} catch (e) {
// Ignore
}
}
async showStats() {
const runtime = (Date.now() - this.metrics.startTime) / 1000;
const balance = await this.wallet.getBalance();
// Calculate real total profit from balance change
const realTotalProfit = this.metrics.startingBalance ? balance.sub(this.metrics.startingBalance) : ethers.BigNumber.from(0);
console.log(`\n${colors.cyan}βββ ULTRA COMPETITIVE BOT STATS βββ${colors.reset}`);
console.log(`${colors.bright}Runtime: ${Math.floor(runtime)}s${colors.reset}`);
console.log(`${colors.green}Successful Settlements: ${this.metrics.settlements}${colors.reset}`);
console.log(`${colors.yellow}Total Attempts: ${this.metrics.settlementAttempts}${colors.reset}`);
console.log(`${colors.red}Failed Attempts: ${this.metrics.failedAttempts}${colors.reset}`);
console.log(`${colors.blue}Events Caught: ${this.metrics.eventsCaught}${colors.reset}`);
console.log(`${colors.magenta}Reversion Checks: ${this.metrics.reversionChecks}${colors.reset}`);
console.log(`${colors.cyan}Active Reports: ${this.activeReports.size}${colors.reset}`);
console.log(`\n${colors.bright}π° PROFIT BREAKDOWN π°${colors.reset}`);
console.log(`${colors.green}Calculated Total Profit: ${ethers.utils.formatEther(this.metrics.totalProfit)} ETH${colors.reset}`);
console.log(`${colors.green}Real Balance Change: ${ethers.utils.formatEther(realTotalProfit)} ETH${colors.reset}`);
console.log(`${colors.red}Gas Spent: ${ethers.utils.formatEther(this.metrics.gasSpent)} ETH${colors.reset}`);
console.log(`${colors.blue}Current Balance: ${ethers.utils.formatEther(balance)} ETH${colors.reset}`);
if (this.metrics.startingBalance) {
console.log(`${colors.dim}Starting Balance: ${ethers.utils.formatEther(this.metrics.startingBalance)} ETH${colors.reset}`);
}
// Show last 5 profits
if (this.metrics.allProfits.length > 0) {
console.log(`\n${colors.bright}π― RECENT SETTLEMENTS π―${colors.reset}`);
const recent = this.metrics.allProfits.slice(-5);
recent.forEach((profit, index) => {
const timeAgo = Math.floor((Date.now() - profit.timestamp) / 1000);
const calculatedETH = ethers.utils.formatEther(profit.calculatedProfit);
const realETH = ethers.utils.formatEther(profit.realProfit);
const status = profit.confirmed ? 'β
' : 'β³';
const blockInfo = profit.block > 0 ? ` Block:${profit.block}` : ' Pending';
console.log(`${colors.green}${status} #${profit.reportId}: ${calculatedETH} ETH (real: ${realETH}) - ${timeAgo}s ago${blockInfo}${colors.reset}`);
});
}
// Show pending vs confirmed breakdown
const confirmedProfits = this.metrics.allProfits.filter(p => p.confirmed);
const pendingProfits = this.metrics.allProfits.filter(p => !p.confirmed);
if (pendingProfits.length > 0 || confirmedProfits.length > 0) {
console.log(`\n${colors.bright}π SETTLEMENT STATUS π${colors.reset}`);
console.log(`${colors.green}Confirmed: ${confirmedProfits.length}${colors.reset}`);
console.log(`${colors.yellow}Pending: ${pendingProfits.length}${colors.reset}`);
}
// Performance metrics
if (this.metrics.settlements > 0) {
const avgProfitPerSettlement = this.metrics.totalProfit.div(this.metrics.settlements);
const successRate = ((this.metrics.settlements / this.metrics.settlementAttempts) * 100).toFixed(1);
console.log(`\n${colors.bright}π PERFORMANCE π${colors.reset}`);
console.log(`${colors.green}Success Rate: ${successRate}%${colors.reset}`);
console.log(`${colors.cyan}Avg Profit/Settlement: ${ethers.utils.formatEther(avgProfitPerSettlement)} ETH${colors.reset}`);
console.log(`${colors.magenta}Settlements/Hour: ${((this.metrics.settlements / runtime) * 3600).toFixed(1)}${colors.reset}`);
}
console.log(`${colors.cyan}βββββββββββββββββββββββββββββββββββ${colors.reset}\n`);
}
async run() {
await this.initialize();
// Show stats every 30 seconds
setInterval(() => {
this.showStats();
}, 30000);
// Scan for existing reports
console.log(`${colors.blue}π Scanning for existing opportunities...${colors.reset}`);
await this.scanExistingReports();
console.log(`${colors.bright}${colors.green}π― BOT IS HUNTING - Press Ctrl+C to stop${colors.reset}\n`);
// Keep running
return new Promise(() => {});
}
async scanExistingReports() {
try {
const nextId = await this.oracle.nextReportId();
const scanRange = Math.min(10, nextId - 1);
for (let id = nextId - 1; id >= nextId - scanRange; id--) {
if (id <= 0) continue;
try {
const [meta, status, extra] = await Promise.all([
this.oracle.reportMeta(id),
this.oracle.reportStatus(id),
this.oracle.extraData(id)
]);
// Skip if processed or has callback
if (status.isSettled || status.isDistributed || extra.callbackContract !== ethers.constants.AddressZero) {
continue;
}
// If has reporter, try immediate settlement
if (status.currentReporter !== ethers.constants.AddressZero) {
await this.attemptSettlement(id.toString());
}
} catch (e) {
// Skip errors
}
}
} catch (e) {
console.log(`${colors.red}Error scanning existing reports: ${e.message}${colors.reset}`);
}
}
}
// Error handling
process.on('unhandledRejection', (error) => {
console.log(`${colors.red}Unhandled rejection: ${error}${colors.reset}`);
});
process.on('SIGINT', async () => {
console.log(`\n${colors.yellow}Shutting down competitive bot...${colors.reset}`);
process.exit(0);
});
// Start bot
if (require.main === module) {
if (!CONFIG.PRIVATE_KEY) {
console.error(`${colors.red}ERROR: BOT_PRIVATE_KEY not set!${colors.reset}`);
process.exit(1);
}
const bot = new CompetitiveBot();
bot.run().catch(error => {
console.error(`${colors.red}Fatal error: ${error}${colors.reset}`);
process.exit(1);
});
}
module.exports = { CompetitiveBot };