-
Notifications
You must be signed in to change notification settings - Fork 1
/
sniper.mjs
355 lines (315 loc) · 10.2 KB
/
sniper.mjs
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
import inquirer from 'inquirer';
import { VersionedTransaction, Connection, Keypair } from '@solana/web3.js';
import WebSocket from 'ws';
import bs58 from 'bs58';
import { logColor } from 'quickcolor';
import fetch from 'node-fetch';
import fs from 'fs';
import dotenv from 'dotenv';
dotenv.config();
// ASCII art
const asciiArt = `
____ ____ ____ ____ ____ __ __ __ __ ____
( ___)( _ \\( ___)( ___)( _ \\( )( )( \\/ )( _ \\
)__) ) / )__) )__) )___/ )(__)( ) ( )___/
(__) (_)_\\)(____)(____)(__) (______)(_/\\/\\_)(__)
Free pump.fun sniper! - By @coinzap
`;
const web3Connection = new Connection(process.env.RPC_ENDPOINT, 'confirmed');
let ws;
const logStream = fs.createWriteStream(process.env.LOG_FILE, { flags: 'a' });
let walletHoldings = {};
let buyingEnabled = process.env.BUYING_ENABLED === 'true';
const lowBalanceThreshold = 0.02 * 1e9;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;
const buys = [];
const sells = [];
const checks = [];
const errors = [];
function log(message, color = 'white', type = 'info') {
const timestamp = new Date().toISOString();
const label = `[${type.toUpperCase()}]`;
logColor(`[${timestamp}] ${label} ${message}`, color);
logStream.write(`[${timestamp}] ${label} ${message}\n`);
switch (type) {
case 'buy':
buys.push({ timestamp, message });
break;
case 'sell':
sells.push({ timestamp, message });
break;
case 'check':
checks.push({ timestamp, message });
break;
case 'error':
errors.push({ timestamp, message });
break;
default:
break;
}
}
function connectWebSocket() {
ws = new WebSocket(process.env.WS_ENDPOINT);
ws.on('open', () => {
log('Connection opened.', 'bright');
subscribeToNewTokens();
reconnectAttempts = 0;
});
ws.on('message', async (data) => {
const newTokenInfo = JSON.parse(data);
if (newTokenInfo.message === 'Successfully subscribed to token creation events.') {
log(`Subscription message: ${newTokenInfo.message}`, 'blue');
} else {
log(`Received new token!: ${JSON.stringify(newTokenInfo)}`, 'blue');
await handleNewToken(newTokenInfo);
}
});
ws.on('error', (error) => {
log(`WebSocket error: ${error.message}`, 'red', 'error');
handleWebSocketError();
});
ws.on('close', () => {
log('WebSocket connection closed. Reconnecting...', 'yellow', 'error');
handleWebSocketError();
});
}
function subscribeToNewTokens() {
const payload = { method: 'subscribeNewToken' };
ws.send(JSON.stringify(payload));
}
function handleWebSocketError() {
if (reconnectAttempts < maxReconnectAttempts) {
reconnectAttempts++;
setTimeout(connectWebSocket, 1000 * reconnectAttempts);
} else {
log('Max reconnection attempts reached. Giving up.', 'red', 'error');
}
}
async function executeBuyOrder(tokenMint) {
if (!buyingEnabled) {
log('Buying is disabled. Skipping buy order.', 'yellow', 'check');
return;
}
try {
const keypair = Keypair.fromSecretKey(bs58.decode(process.env.WALLET_PRIVATE_KEY));
const balance = await web3Connection.getBalance(keypair.publicKey);
if (balance < lowBalanceThreshold) {
log(`Low balance detected: ${balance} only available, Quitting.`, 'red', 'error');
return;
}
const response = await fetch('https://pumpportal.fun/api/trade-local', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
publicKey: process.env.WALLET_PUBLIC_KEY,
action: 'buy',
mint: tokenMint,
denominatedInSol: 'true',
amount: process.env.INVESTMENT_AMOUNT,
slippage: process.env.SLIPPAGE_TOLERANCE,
priorityFee: 0.005, // Worked the best for me
pool: 'pump',
}),
});
if (response.status === 200) {
const data = await response.arrayBuffer();
const tx = VersionedTransaction.deserialize(new Uint8Array(data));
tx.sign([keypair]);
const signature = await web3Connection.sendTransaction(tx);
log(`Transaction successful: https://solscan.io/tx/${signature}`, 'green', 'buy');
trackTokenHoldings(tokenMint);
const autoSellDelay = parseInt(process.env.AUTO_SELL_DELAY_MS, 10) || 30000; // Default to 30 seconds, if nothing is set!
setTimeout(async () => {
log(`${autoSellDelay / 1000} seconds passed since purchase. Executing sell order for ${tokenMint}.`, 'yellow', 'sell');
await executeSellOrder(tokenMint, process.env.INVESTMENT_AMOUNT);
}, autoSellDelay);
} else {
log(`Trade request failed: ${response.statusText}`, 'red', 'error');
subscribeToNewTokens();
}
} catch (error) {
log(`Error executing buy order: ${error.message}`, 'red', 'error');
subscribeToNewTokens();
}
}
async function executeSellOrder(tokenMint, amount) {
try {
const keypair = Keypair.fromSecretKey(bs58.decode(process.env.WALLET_PRIVATE_KEY));
const response = await fetch('https://pumpportal.fun/api/trade-local', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
publicKey: process.env.WALLET_PUBLIC_KEY,
action: 'sell',
mint: tokenMint,
denominatedInSol: 'true',
amount: amount,
slippage: process.env.SLIPPAGE_TOLERANCE,
priorityFee: 0.001, // Important the sell goes through
pool: "pump",
}),
});
if (response.status === 200) {
const data = await response.arrayBuffer();
const tx = VersionedTransaction.deserialize(new Uint8Array(data));
tx.sign([keypair]);
const signature = await web3Connection.sendTransaction(tx);
log(`Sell transaction successful: https://solscan.io/tx/${signature}`, 'green', 'sell');
} else {
log(`Trade request failed: ${response.statusText}`, 'red', 'error');
}
} catch (error) {
log(`Error executing sell order: ${error.message}`, 'red', 'error');
}
}
function trackTokenHoldings(tokenMint) {
if (!walletHoldings[tokenMint]) {
walletHoldings[tokenMint] = {
amount: process.env.INVESTMENT_AMOUNT,
initialPrice: process.env.INVESTMENT_AMOUNT,
highestPrice: process.env.INVESTMENT_AMOUNT,
};
}
}
async function handleNewToken(newTokenInfo) {
const tokenMint = newTokenInfo.mint;
if (tokenMint) {
log(`Newly minted token detected: ${tokenMint}`, 'cyan', 'check');
await executeBuyOrder(tokenMint);
} else {
log(`Invalid or duplicate token data received: ${JSON.stringify(newTokenInfo)}`, 'red', 'error');
}
}
process.on('unhandledRejection', (error) => {
log(`Unhandled promise rejection: ${error.message}`, 'red', 'error');
});
process.on('uncaughtException', (error) => {
log(`Uncaught exception: ${error.message}`, 'red', 'error');
});
const readConfig = () => {
return {
rpc_endpoint: process.env.RPC_ENDPOINT,
ws_endpoint: process.env.WS_ENDPOINT,
log_file: process.env.LOG_FILE,
buying_enabled: process.env.BUYING_ENABLED,
investment_amount: process.env.INVESTMENT_AMOUNT,
slippage_tolerance: process.env.SLIPPAGE_TOLERANCE,
wallet_credentials: {
public_key: process.env.WALLET_PUBLIC_KEY,
private_key: process.env.WALLET_PRIVATE_KEY,
},
retry_attempts: process.env.RETRY_ATTEMPTS,
retry_delay: process.env.RETRY_DELAY,
auto_sell_delay_ms: process.env.AUTO_SELL_DELAY_MS,
};
};
const writeConfig = (newConfig) => {
fs.writeFileSync('.env', Object.entries(newConfig).map(([key, value]) => `${key}=${value}`).join('\n'), 'utf-8');
};
const editConfig = async () => {
const config = readConfig();
const answers = await inquirer.prompt([
{
type: 'input',
name: 'RPC_ENDPOINT',
message: 'Enter RPC endpoint:',
default: config.rpc_endpoint,
},
{
type: 'input',
name: 'WS_ENDPOINT',
message: 'Enter WebSocket endpoint:',
default: config.ws_endpoint,
},
{
type: 'input',
name: 'LOG_FILE',
message: 'Enter log file path:',
default: config.log_file,
},
{
type: 'confirm',
name: 'BUYING_ENABLED',
message: 'Enable buying?',
default: config.buying_enabled,
},
{
type: 'input',
name: 'INVESTMENT_AMOUNT',
message: 'Enter investment amount:',
default: config.investment_amount,
},
{
type: 'input',
name: 'SLIPPAGE_TOLERANCE',
message: 'Enter slippage tolerance:',
default: config.slippage_tolerance,
},
{
type: 'input',
name: 'WALLET_PUBLIC_KEY',
message: 'Enter wallet public key:',
default: config.wallet_credentials.public_key,
},
{
type: 'input',
name: 'WALLET_PRIVATE_KEY',
message: 'Enter wallet private key:',
default: config.wallet_credentials.private_key,
},
{
type: 'input',
name: 'RETRY_ATTEMPTS',
message: 'Enter number of retry attempts:',
default: config.retry_attempts,
},
{
type: 'input',
name: 'RETRY_DELAY',
message: 'Enter retry delay in milliseconds:',
default: config.retry_delay,
},
{
type: 'input',
name: 'AUTO_SELL_DELAY_MS',
message: 'Enter auto-sell delay in milliseconds:',
default: config.auto_sell_delay_ms || 30000,
},
]);
writeConfig(answers);
console.log('Configuration updated successfully.');
mainMenu();
};
const initializeBot = () => {
log('Bot started.', 'green');
connectWebSocket();
};
const mainMenu = async () => {
const answer = await inquirer.prompt([
{
type: 'list',
name: 'menuOption',
message: 'Select an option:',
choices: [
'Start',
'Edit Config',
'Exit'
],
},
]);
switch (answer.menuOption) {
case 'Start':
initializeBot();
break;
case 'Edit Config':
await editConfig();
break;
case 'Exit':
console.log('Exiting...');
process.exit(0);
}
};
console.clear();
logColor(asciiArt, 'blue');
mainMenu();