-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot-runner.js
More file actions
493 lines (401 loc) · 17.7 KB
/
Copy pathbot-runner.js
File metadata and controls
493 lines (401 loc) · 17.7 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
require('dotenv').config();
const { ethers } = require('ethers');
const winston = require('winston');
const axios = require('axios');
// Configuration
const CONFIG = {
// CRITICAL: Use a separate wallet with minimal funds!
PRIVATE_KEY: process.env.BOT_PRIVATE_KEY || '',
// Network settings - Multiple RPCs for redundancy
RPC_URLS: [
process.env.RPC_URL,
'https://g.w.lavanet.xyz:443/gateway/arb1/rpc-http/f7ee0000000000000000000000000000', // Lava as primary
'https://arb1.arbitrum.io/rpc',
'https://arbitrum-one.public.blastapi.io',
'https://endpoints.omniatech.io/v1/arbitrum/one/public',
'https://arb-mainnet.g.alchemy.com/v2/demo',
'https://arbitrum.blockpi.network/v1/rpc/public',
'https://1rpc.io/arb',
'https://rpc.ankr.com/arbitrum',
'https://arb1.arbitrum.io/rpc'
].filter(Boolean), // Remove any undefined values
CHAIN_ID: 42161, // Arbitrum One
// Contract addresses
ORACLE_ADDRESS: '0xa935db8cb0f45256e3df77cbff1980cf7aeffbe4',
BOT_CONTRACT: process.env.BOT_CONTRACT || '', // Your deployed CompetitiveSettleBot
// Bot parameters
MAX_GAS_PRICE: ethers.utils.parseUnits('0.1', 'gwei'), // Arbitrum has low gas
MIN_PROFIT_WEI: ethers.utils.parseEther('0.0001'), // 0.0001 ETH minimum
SCAN_INTERVAL: 1000, // 1 second
BATCH_SIZE: 10,
// MEV Protection
USE_PRIVATE_MEMPOOL: true,
// Monitoring
DISCORD_WEBHOOK: process.env.DISCORD_WEBHOOK || '',
ENABLE_MONITORING: true,
// Safety
MAX_REPORTS_PER_BLOCK: 5,
EMERGENCY_STOP: false
};
// Logger setup
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'bot.log' })
]
});
// Contract ABIs
const ORACLE_ABI = [
"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)"
];
const BOT_ABI = [
"function flashSettle(uint256[] calldata ids) external",
"function smartSettle(uint256 maxGasPrice, uint256 minProfit) external",
"function mevProtectedSettle(uint256[] calldata ids, bytes32 commitment) external",
"function batchSettle(uint256 startId, uint256 count) external"
];
class SettlementBot {
constructor() {
this.rpcIndex = 0;
this.provider = this.createProvider();
this.wallet = new ethers.Wallet(CONFIG.PRIVATE_KEY, this.provider);
this.oracle = new ethers.Contract(CONFIG.ORACLE_ADDRESS, ORACLE_ABI, this.provider);
this.bot = CONFIG.BOT_CONTRACT ? new ethers.Contract(CONFIG.BOT_CONTRACT, BOT_ABI, this.wallet) : null;
this.processedReports = new Set();
this.pendingTxs = new Set();
this.profitTracker = {
total: ethers.BigNumber.from(0),
count: 0,
startTime: Date.now()
};
// Performance metrics
this.metrics = {
scans: 0,
settlements: 0,
failures: 0,
gasSpent: ethers.BigNumber.from(0),
avgSettleTime: 0,
rpcFailures: 0
};
}
createProvider() {
const rpcUrl = CONFIG.RPC_URLS[this.rpcIndex % CONFIG.RPC_URLS.length];
logger.info(`Using RPC: ${rpcUrl}`);
const provider = new ethers.providers.JsonRpcProvider({
url: rpcUrl,
timeout: 10000, // 10 second timeout
throttleLimit: 1 // Prevent rate limiting
});
// Add error handling for provider
provider.on('error', (error) => {
logger.error(`RPC Error with ${rpcUrl}:`, error.message);
this.handleRpcError();
});
return provider;
}
async handleRpcError() {
this.metrics.rpcFailures++;
this.rpcIndex++;
logger.warn(`Switching to next RPC endpoint (${this.rpcIndex % CONFIG.RPC_URLS.length})`);
// Create new provider with next RPC
this.provider = this.createProvider();
// Update wallet and contracts with new provider
this.wallet = new ethers.Wallet(CONFIG.PRIVATE_KEY, this.provider);
this.oracle = new ethers.Contract(CONFIG.ORACLE_ADDRESS, ORACLE_ABI, this.provider);
if (CONFIG.BOT_CONTRACT) {
this.bot = new ethers.Contract(CONFIG.BOT_CONTRACT, BOT_ABI, this.wallet);
}
// Wait a moment before retrying
await this.sleep(1000);
}
async safeProviderCall(fn, maxRetries = 3) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
lastError = error;
logger.warn(`Provider call failed (attempt ${i + 1}/${maxRetries}):`, error.message);
if (i < maxRetries - 1) {
await this.handleRpcError();
}
}
}
throw lastError;
}
async initialize() {
logger.info('Initializing Settlement Bot...');
logger.info(`Available RPC endpoints: ${CONFIG.RPC_URLS.length}`);
// Verify wallet balance with retry
const balance = await this.safeProviderCall(() => this.wallet.getBalance());
logger.info(`Wallet balance: ${ethers.utils.formatEther(balance)} ETH`);
if (balance.lt(ethers.utils.parseEther('0.01'))) {
logger.warn('Low wallet balance! Minimum 0.01 ETH recommended');
}
// Verify contracts with retry
const nextId = await this.safeProviderCall(() => this.oracle.nextReportId());
logger.info(`Oracle next report ID: ${nextId}`);
if (this.bot) {
const code = await this.safeProviderCall(() => this.provider.getCode(CONFIG.BOT_CONTRACT));
if (code === '0x') {
throw new Error('Bot contract not deployed!');
}
}
logger.info('Bot initialized successfully');
}
async scanForOpportunities() {
try {
this.metrics.scans++;
const [nextId, currentBlock] = await this.safeProviderCall(async () => {
return Promise.all([
this.oracle.nextReportId(),
this.provider.getBlockNumber()
]);
});
const currentTime = Math.floor(Date.now() / 1000);
const opportunities = [];
const scanRange = Math.min(50, nextId - 1);
// Parallel scanning for efficiency
const promises = [];
for (let i = 0; i < scanRange; i++) {
const reportId = nextId - 1 - i;
if (reportId <= 0 || this.processedReports.has(reportId)) continue;
promises.push(this.checkReport(reportId, currentBlock, currentTime));
}
const results = await Promise.all(promises);
results.forEach(opp => {
if (opp) opportunities.push(opp);
});
// Sort by profitability
opportunities.sort((a, b) => b.estimatedProfit.sub(a.estimatedProfit).toNumber());
return opportunities;
} catch (error) {
logger.error('Scan error:', error);
return [];
}
}
async checkReport(reportId, currentBlock, currentTime) {
try {
const [meta, status, extraData] = await Promise.all([
this.oracle.reportMeta(reportId),
this.oracle.reportStatus(reportId),
this.oracle.extraData(reportId)
]);
// Skip if already settled/distributed or has callback
if (status.isSettled || status.isDistributed || extraData.callbackContract !== ethers.constants.AddressZero) {
return null;
}
// Check if settleable
const settlementTime = meta.timeType ? currentTime : currentBlock;
const deadline = status.reportTimestamp.add(meta.settlementTime);
if (settlementTime.lt(deadline)) {
return null;
}
// Estimate profitability
const gasPrice = await this.provider.getGasPrice();
const estimatedGas = 150000; // Conservative estimate
const gasCost = gasPrice.mul(estimatedGas);
const estimatedProfit = meta.settlerReward.sub(gasCost);
// Check minimum profit
if (estimatedProfit.lt(CONFIG.MIN_PROFIT_WEI)) {
return null;
}
return {
reportId,
reward: meta.settlerReward,
estimatedProfit,
estimatedGas,
deadline: deadline.toNumber(),
priority: this.calculatePriority(meta, status, estimatedProfit)
};
} catch (error) {
return null;
}
}
calculatePriority(meta, status, profit) {
// Higher priority for:
// 1. Higher profit
// 2. Closer to deadline
// 3. No disputes
let priority = profit.div(1e15).toNumber(); // Base on profit in finney
if (!status.disputeOccurred) {
priority += 10; // Bonus for no disputes
}
const timeLeft = meta.settlementTime.sub(Date.now() / 1000 - status.reportTimestamp);
if (timeLeft.lt(300)) { // Less than 5 minutes
priority += 20;
}
return priority;
}
async executeSettlements(opportunities) {
if (opportunities.length === 0 || CONFIG.EMERGENCY_STOP) return;
// Limit settlements per block
const toSettle = opportunities.slice(0, CONFIG.MAX_REPORTS_PER_BLOCK);
if (this.bot) {
// Use optimized bot contract
await this.executeBotSettlement(toSettle);
} else {
// Direct settlement
await this.executeDirectSettlement(toSettle);
}
}
async executeBotSettlement(opportunities) {
const reportIds = opportunities.map(o => o.reportId);
try {
const gasPrice = await this.provider.getGasPrice();
if (gasPrice.gt(CONFIG.MAX_GAS_PRICE)) {
logger.warn('Gas price too high, skipping');
return;
}
// Use flashSettle for speed
const tx = await this.bot.flashSettle(reportIds, {
gasPrice: gasPrice.mul(110).div(100), // 10% higher for priority
gasLimit: 500000 * reportIds.length
});
logger.info(`Bot settlement tx: ${tx.hash}`);
this.pendingTxs.add(tx.hash);
// Don't wait for confirmation - move on to next scan
tx.wait().then(receipt => {
this.handleSettlementReceipt(receipt, reportIds);
this.pendingTxs.delete(tx.hash);
}).catch(error => {
logger.error('Settlement failed:', error);
this.metrics.failures++;
this.pendingTxs.delete(tx.hash);
});
} catch (error) {
logger.error('Bot settlement error:', error);
this.metrics.failures++;
}
}
async executeDirectSettlement(opportunities) {
for (const opp of opportunities) {
if (this.pendingTxs.size >= 3) break; // Limit concurrent txs
try {
const gasPrice = await this.provider.getGasPrice();
if (gasPrice.gt(CONFIG.MAX_GAS_PRICE)) continue;
const tx = await this.oracle.settle(opp.reportId, {
gasPrice: gasPrice.mul(110).div(100),
gasLimit: 200000
});
logger.info(`Direct settlement tx: ${tx.hash} for report ${opp.reportId}`);
this.pendingTxs.add(tx.hash);
tx.wait().then(receipt => {
this.handleSettlementReceipt(receipt, [opp.reportId]);
this.pendingTxs.delete(tx.hash);
}).catch(error => {
logger.error(`Settlement ${opp.reportId} failed:`, error);
this.pendingTxs.delete(tx.hash);
});
} catch (error) {
logger.error(`Failed to settle ${opp.reportId}:`, error);
}
}
}
async handleSettlementReceipt(receipt, reportIds) {
const gasUsed = receipt.gasUsed;
const gasPrice = receipt.effectiveGasPrice;
const gasCost = gasUsed.mul(gasPrice);
this.metrics.gasSpent = this.metrics.gasSpent.add(gasCost);
this.metrics.settlements += reportIds.length;
// Mark as processed
reportIds.forEach(id => this.processedReports.add(id));
// Calculate profit (simplified)
const balanceAfter = await this.wallet.getBalance();
logger.info(`Settlement complete: ${reportIds.length} reports, gas: ${ethers.utils.formatEther(gasCost)} ETH`);
// Alert on Discord if configured
if (CONFIG.DISCORD_WEBHOOK && CONFIG.ENABLE_MONITORING) {
this.sendAlert(`💰 Settlement Success\nReports: ${reportIds.join(', ')}\nGas Cost: ${ethers.utils.formatEther(gasCost)} ETH`);
}
}
async sendAlert(message) {
try {
await axios.post(CONFIG.DISCORD_WEBHOOK, {
content: message,
username: 'Settlement Bot'
});
} catch (error) {
logger.error('Discord alert failed:', error.message);
}
}
async run() {
await this.initialize();
logger.info('Starting main loop...');
// Main loop
while (true) {
try {
const opportunities = await this.scanForOpportunities();
if (opportunities.length > 0) {
logger.info(`Found ${opportunities.length} opportunities`);
await this.executeSettlements(opportunities);
}
// Performance logging
if (this.metrics.scans % 100 === 0) {
this.logPerformance();
}
await this.sleep(CONFIG.SCAN_INTERVAL);
} catch (error) {
logger.error('Main loop error:', error);
await this.sleep(5000); // Wait longer on error
}
}
}
logPerformance() {
const runtime = (Date.now() - this.profitTracker.startTime) / 1000 / 60; // minutes
const avgGasPerSettle = this.metrics.settlements > 0
? this.metrics.gasSpent.div(this.metrics.settlements)
: ethers.BigNumber.from(0);
const currentRpc = CONFIG.RPC_URLS[this.rpcIndex % CONFIG.RPC_URLS.length];
logger.info({
message: 'Performance Report',
scans: this.metrics.scans,
settlements: this.metrics.settlements,
failures: this.metrics.failures,
rpcFailures: this.metrics.rpcFailures,
currentRpc: currentRpc.replace(/https?:\/\//, '').split('/')[0], // Show domain only
totalGasSpent: ethers.utils.formatEther(this.metrics.gasSpent),
avgGasPerSettle: ethers.utils.formatEther(avgGasPerSettle),
runtime: `${runtime.toFixed(2)} minutes`,
settlementsPerMinute: (this.metrics.settlements / runtime).toFixed(2)
});
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Error handling
process.on('unhandledRejection', (error) => {
logger.error('Unhandled rejection:', error);
});
process.on('uncaughtException', (error) => {
logger.error('Uncaught exception:', error);
process.exit(1);
});
// Graceful shutdown
process.on('SIGINT', async () => {
logger.info('Shutting down...');
process.exit(0);
});
// Start bot
if (require.main === module) {
if (!CONFIG.PRIVATE_KEY) {
console.error('ERROR: BOT_PRIVATE_KEY environment variable not set!');
console.error('NEVER use your main wallet! Create a dedicated bot wallet.');
process.exit(1);
}
const bot = new SettlementBot();
bot.run().catch(error => {
logger.error('Fatal error:', error);
process.exit(1);
});
}
module.exports = { SettlementBot };