forked from Rust-Sol-Dev/solana-pumpfun-snipe-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pump_fun.js
878 lines (764 loc) · 35.3 KB
/
pump_fun.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
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
const {
Connection,
PublicKey,
SystemProgram,
clusterApiUrl,
LAMPORTS_PER_SOL,
TransactionInstruction,
Keypair,
Transaction,
sendAndConfirmTransaction,
ComputeBudgetProgram,
SendTransactionError
} = require('@solana/web3.js');
const { confirm_transaction } = require('sol-web3-1.48');
const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');
const GLOBAL = new PublicKey("4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf");
const FEE_RECIPIENT = new PublicKey("CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbicfhtW4xC9iM");
const TOKEN_PROGRAM_ID = new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
const ASSOC_TOKEN_ACC_PROG = new PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
const RENT = new PublicKey("SysvarRent111111111111111111111111111111111");
const PUMP_FUN_PROGRAM = new PublicKey("6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P");
const PUMP_FUN_ACCOUNT = new PublicKey("Ce6TQqeHC9p8KetsN6JsjHK7UTZk7nasjjnr7XxXp9F1");
const SYSTEM_PROGRAM_ID = SystemProgram.programId;
const PRIVATE_KEY = 'YOUR_PRIVATE_KEY_HERE';
const CUSTOM_RPC_URL = 'YOUR_RPC_URL_HERE';
const STATE_FILE = path.join(__dirname, 'purchasedCoins.json');
const SETTINGS_FILE = path.join(__dirname, 'settings.json');
let autoBuyRunning = false;
const savePurchasedCoins = (coins) => {
fs.writeFileSync(STATE_FILE, JSON.stringify(coins, null, 2), 'utf-8');
};
const loadPurchasedCoins = () => {
if (fs.existsSync(STATE_FILE)) {
const data = fs.readFileSync(STATE_FILE, 'utf-8');
return JSON.parse(data);
}
return [];
};
const saveSettings = (settings) => {
fs.writeFileSync(SETTINGS_FILE, JSON.stringify(settings, null, 2), 'utf-8');
};
const loadSettings = () => {
if (fs.existsSync(SETTINGS_FILE)) {
const data = fs.readFileSync(SETTINGS_FILE, 'utf-8');
return JSON.parse(data);
}
return {
auto: false,
buyAmount: 0.1,
takeProfitEnabled: false,
takeProfitPercentage: 10,
stopLossEnabled: false,
stopLossPercentage: 10,
min_usd_market_cap: 0,
min_reply_count: 0,
require_website: false,
require_twitter: false,
require_telegram: false,
require_revoked_authority: false
};
};
let purchasedCoins = loadPurchasedCoins();
let settings = loadSettings();
const getKeyPairFromPrivateKey = async (key) => {
const { default: bs58 } = await import('bs58');
return Keypair.fromSecretKey(new Uint8Array(bs58.decode(key)));
};
const bufferFromUInt64 = (value) => {
let buffer = Buffer.alloc(8);
buffer.writeBigUInt64LE(BigInt(value));
return buffer;
};
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const getLatestCoin = async (limit = 1) => {
const response = await fetch(`https://frontend-api.pump.fun/coins?offset=0&limit=${limit}&sort=created_timestamp&order=DESC&includeNsfw=true`);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
};
const getCoinData = async (mint) => {
const response = await fetch(`https://frontend-api.pump.fun/coins/${mint}`);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
};
const getKingOfTheHillCoin = async () => {
const response = await fetch('https://frontend-api.pump.fun/coins/king-of-the-hill');
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
};
const fetchLatestCoins = async (limit = 40) => {
const response = await fetch(`https://frontend-api.pump.fun/coins?offset=0&limit=${limit}&sort=created_timestamp&order=DESC&includeNsfw=true`);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
};
const checkIfAuthoritiesRevoked = async (mintAddress) => {
const connection = new Connection(CUSTOM_RPC_URL || clusterApiUrl("mainnet-beta"), 'confirmed');
const mintPubkey = new PublicKey(mintAddress);
const mintInfo = await connection.getParsedAccountInfo(mintPubkey, 'confirmed');
if (mintInfo && mintInfo.value) {
const { data } = mintInfo.value;
const { mintAuthority, freezeAuthority } = data.parsed.info;
return !mintAuthority && !freezeAuthority;
}
return false;
};
const createTransaction = async (connection, instructions, payer, priorityFeeInSol = 0) => {
const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({ units: 1400000 });
const transaction = new Transaction().add(modifyComputeUnits);
if (priorityFeeInSol > 0) {
const microLamports = priorityFeeInSol * 1_000_000_000;
const addPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({ microLamports });
transaction.add(addPriorityFee);
}
transaction.add(...instructions);
transaction.feePayer = payer;
transaction.recentBlockhash = (await connection.getLatestBlockhash('finalized')).blockhash;
return transaction;
};
const sendAndConfirmTransactionWrapper = async (connection, transaction, signers, maxRetries = 1, timeout = 15000) => {
for (let attempt = 0; attempt < maxRetries + 1; attempt++) {
try {
const controller = new AbortController();
const signal = controller.signal;
const timeoutId = setTimeout(() => controller.abort(), timeout);
const signature = await sendAndConfirmTransaction(connection, transaction, signers, {
skipPreflight: true,
preflightCommitment: 'confirmed',
commitment: 'confirmed',
signal
});
clearTimeout(timeoutId);
return signature;
} catch (error) {
if (attempt === maxRetries || error.name === 'AbortError') {
console.error(`Transaction failed after ${attempt + 1} attempts:`, error);
return null;
}
await sleep(2000);
transaction.recentBlockhash = (await connection.getLatestBlockhash('finalized')).blockhash;
}
}
return null;
};
const displayLatestCoins = async (limit = 20) => {
const latestCoins = await fetchLatestCoins(limit * 2); // Fetch more to filter
const filteredCoins = await filterCoins(latestCoins).then(coins => coins.slice(0, limit));
if (filteredCoins.length === 0) {
console.log('No coins matched the filter criteria.');
return null;
}
const inquirer = await import('inquirer');
const answers = await inquirer.default.prompt([
{
type: 'list',
name: 'selectedCoin',
message: 'Select a coin to view details or return to menu:',
choices: filteredCoins.map((coin, index) => ({
name: `${coin.name} (${coin.symbol})`,
value: index
})).concat({ name: 'Return to menu', value: 'return' })
}
]);
return answers.selectedCoin === 'return' ? null : filteredCoins[answers.selectedCoin];
};
const displayCoinDetails = async (coin) => {
const connection = new Connection(CUSTOM_RPC_URL || clusterApiUrl("mainnet-beta"), 'confirmed');
const isRevoked = await checkIfAuthoritiesRevoked(coin.mint);
console.log(`
Name: ${coin.name}
Symbol: ${coin.symbol}
Description: ${coin.description}
Creator: ${coin.creator}
USD Market Cap: ${coin.usd_market_cap}
SOL Market Cap: ${coin.market_cap}
Created At: ${new Date(coin.created_timestamp).toLocaleString()}
Twitter: ${coin.twitter || 'N/A'}
Telegram: ${coin.telegram || 'N/A'}
Website: ${coin.website || 'N/A'}
Freeze and Mint Authority Revoked: ${isRevoked ? 'Yes' : 'No'}
`);
const inquirer = await import('inquirer');
const answers = await inquirer.default.prompt([
{
type: 'list',
name: 'action',
message: `What would you like to do with ${coin.name}?`,
choices: [
{ name: 'Buy this coin', value: 'buy' },
{ name: 'Return to latest coins', value: 'return' }
]
}
]);
return answers.action;
};
const buyCoin = async (connection, payer, coinData, solIn, priorityFeeInSol = 0.001, slippageDecimal = 0.25) => {
try {
const { PublicKey, TransactionInstruction, SystemProgram, SendTransactionError } = await import('@solana/web3.js');
const { getAssociatedTokenAddress, createAssociatedTokenAccountInstruction } = await import('@solana/spl-token');
const owner = payer.publicKey;
const mintPubkey = new PublicKey(coinData.mint);
const tokenAccountAddress = await getAssociatedTokenAddress(mintPubkey, owner, false);
const tokenAccountInfo = await connection.getAccountInfo(tokenAccountAddress);
const instructions = [];
if (!tokenAccountInfo) {
instructions.push(
createAssociatedTokenAccountInstruction(
payer.publicKey,
tokenAccountAddress,
payer.publicKey,
mintPubkey
)
);
}
const solInLamports = solIn * LAMPORTS_PER_SOL;
const tokenOut = Math.floor(solInLamports * coinData.virtual_token_reserves / coinData.virtual_sol_reserves);
const solInWithSlippage = solIn * (1 + slippageDecimal);
const maxSolCost = Math.floor(solInWithSlippage * LAMPORTS_PER_SOL);
const keys = [
{ pubkey: GLOBAL, isSigner: false, isWritable: false },
{ pubkey: FEE_RECIPIENT, isSigner: false, isWritable: true },
{ pubkey: mintPubkey, isSigner: false, isWritable: false },
{ pubkey: new PublicKey(coinData.bonding_curve), isSigner: false, isWritable: true },
{ pubkey: new PublicKey(coinData.associated_bonding_curve), isSigner: false, isWritable: true },
{ pubkey: tokenAccountAddress, isSigner: false, isWritable: true },
{ pubkey: owner, isSigner: false, isWritable: true },
{ pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
{ pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },
{ pubkey: RENT, isSigner: false, isWritable: false },
{ pubkey: PUMP_FUN_ACCOUNT, isSigner: false, isWritable: false },
{ pubkey: PUMP_FUN_PROGRAM, isSigner: false, isWritable: false }
];
const data = Buffer.concat([
bufferFromUInt64("16927863322537952870"),
bufferFromUInt64(tokenOut),
bufferFromUInt64(maxSolCost)
]);
const instruction = new TransactionInstruction({
keys: keys,
programId: PUMP_FUN_PROGRAM,
data: data
});
instructions.push(instruction);
const transaction = await createTransaction(connection, instructions, payer.publicKey, priorityFeeInSol);
const signature = await sendAndConfirmTransactionWrapper(connection, transaction, [payer]);
if (signature) {
console.log('Buy transaction confirmed:', signature);
return tokenOut;
} else {
console.error('Buy transaction failed.');
return null;
}
} catch (error) {
console.error('Error buying coin:', error);
return null;
}
};
const sellCoin = async (connection, payer, coinData, tokenBalance, priorityFeeInSol = 0.001) => {
try {
const { PublicKey, TransactionInstruction, SystemProgram, SendTransactionError } = await import('@solana/web3.js');
const { getAssociatedTokenAddress } = await import('@solana/spl-token');
const owner = payer.publicKey;
const mintPubkey = new PublicKey(coinData.mint);
const tokenAccountAddress = await getAssociatedTokenAddress(mintPubkey, owner, false);
const minSolOutput = Math.floor(tokenBalance * 0.9 * coinData.virtual_sol_reserves / coinData.virtual_token_reserves);
const keys = [
{ pubkey: GLOBAL, isSigner: false, isWritable: false },
{ pubkey: FEE_RECIPIENT, isSigner: false, isWritable: true },
{ pubkey: mintPubkey, isSigner: false, isWritable: false },
{ pubkey: new PublicKey(coinData.bonding_curve), isSigner: false, isWritable: true },
{ pubkey: new PublicKey(coinData.associated_bonding_curve), isSigner: false, isWritable: true },
{ pubkey: tokenAccountAddress, isSigner: false, isWritable: true },
{ pubkey: owner, isSigner: false, isWritable: true },
{ pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
{ pubkey: ASSOC_TOKEN_ACC_PROG, isSigner: false, isWritable: false },
{ pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },
{ pubkey: PUMP_FUN_ACCOUNT, isSigner: false, isWritable: false },
{ pubkey: PUMP_FUN_PROGRAM, isSigner: false, isWritable: false }
];
const data = Buffer.concat([
bufferFromUInt64("12502976635542562355"),
bufferFromUInt64(tokenBalance),
bufferFromUInt64(minSolOutput)
]);
const instruction = new TransactionInstruction({ keys, programId: PUMP_FUN_PROGRAM, data });
const transaction = await createTransaction(connection, [instruction], payer.publicKey, priorityFeeInSol);
const signature = await sendAndConfirmTransactionWrapper(connection, transaction, [payer]);
console.log('Sell transaction confirmed:', signature);
return minSolOutput;
} catch (error) {
if (error instanceof SendTransactionError) {
console.error('SendTransactionError:', error);
const logs = await connection.getConfirmedTransaction(error.signature);
if (logs) {
console.error('Transaction logs:', logs.meta.logMessages);
} else {
console.error('Failed to retrieve transaction logs.');
}
} else {
console.error('Detailed error in sellCoin:', error);
}
throw error;
}
};
const monitorAndSell = (connection, payer, mint, boughtTokens, buyPrice) => {
const targetPrice = buyPrice * (1 + settings.takeProfitPercentage / 100);
const stopLossPrice = buyPrice * (1 - settings.stopLossPercentage / 100);
const intervalId = setInterval(async () => {
try {
const coinData = await getCoinData(mint);
const currentPrice = coinData.market_cap / coinData.total_supply;
if (currentPrice >= targetPrice && settings.takeProfitEnabled) {
console.log('Target price reached. Selling...');
await sellCoin(connection, payer, coinData, boughtTokens);
clearInterval(intervalId);
} else if (currentPrice <= stopLossPrice && settings.stopLossEnabled) {
console.log('Stop loss price reached. Selling...');
await sellCoin(connection, payer, coinData, boughtTokens);
clearInterval(intervalId);
}
} catch (error) {
console.error('Error in monitoring loop:', error);
}
}, 10000);
};
const viewPositions = async (connection, payer) => {
const inquirer = await import('inquirer');
while (true) {
const choices = purchasedCoins.map((coin, index) => ({
name: `${coin.name} (${coin.symbol})`,
value: index
}));
choices.push({ name: 'Sell All', value: 'sell_all' });
choices.push({ name: 'Return to menu', value: 'return' });
const answers = await inquirer.default.prompt([
{
type: 'list',
name: 'selectedCoin',
message: 'Select a position to view or manage:',
choices: choices
}
]);
if (answers.selectedCoin === 'return') {
break;
} else if (answers.selectedCoin === 'sell_all') {
for (const coin of purchasedCoins) {
const coinData = await getCoinData(coin.mint);
await sellCoin(connection, payer, coinData, coin.amount);
console.log(`Sold ${coin.amount} tokens of ${coin.name} (${coin.symbol}).`);
}
purchasedCoins = [];
savePurchasedCoins(purchasedCoins);
break;
}
const coin = purchasedCoins[answers.selectedCoin];
while (true) {
const coinData = await getCoinData(coin.mint);
const currentPrice = coinData.market_cap / coinData.total_supply;
const targetPrice = coin.price * (1 + settings.takeProfitPercentage / 100);
const initialPositionValue = coin.amount * coin.price;
const currentPositionValue = coin.amount * currentPrice;
console.log(`
Coin: ${coin.name} (${coin.symbol})
Initial Purchase Price: ${coin.price.toFixed(12)} SOL
Current Price: ${currentPrice.toFixed(12)} SOL
Intended Price: ${targetPrice.toFixed(12)} SOL
Initial Position Value: ${initialPositionValue.toFixed(9)} SOL
Current Position Value: ${currentPositionValue.toFixed(9)} SOL
`);
const manageAnswers = await inquirer.default.prompt([
{
type: 'list',
name: 'action',
message: 'Select an action:',
choices: [
{ name: 'Sell now', value: 'sell' },
{ name: 'Refresh', value: 'refresh' },
{ name: 'Return to positions', value: 'return' }
]
}
]);
if (manageAnswers.action === 'sell') {
await sellCoin(connection, payer, coinData, coin.amount);
console.log(`Sold ${coin.amount} tokens of ${coin.name} (${coin.symbol}).`);
purchasedCoins.splice(answers.selectedCoin, 1);
savePurchasedCoins(purchasedCoins);
break;
} else if (manageAnswers.action === 'return') {
break;
} else if (manageAnswers.action === 'refresh') {
console.log('Refreshing...');
}
}
}
};
const setSettings = async () => {
const inquirer = await import('inquirer');
const answers = await inquirer.default.prompt([
{
type: 'input',
name: 'min_usd_market_cap',
message: 'Set minimum USD market cap:',
default: settings.min_usd_market_cap,
validate: (value) => !isNaN(value) && value >= 0
},
{
type: 'input',
name: 'min_reply_count',
message: 'Set minimum reply count:',
default: settings.min_reply_count,
validate: (value) => !isNaN(value) && value >= 0
},
{
type: 'confirm',
name: 'require_website',
message: 'Require website:',
default: settings.require_website
},
{
type: 'confirm',
name: 'require_twitter',
message: 'Require Twitter:',
default: settings.require_twitter
},
{
type: 'confirm',
name: 'require_telegram',
message: 'Require Telegram:',
default: settings.require_telegram
},
{
type: 'confirm',
name: 'require_revoked_authority',
message: 'Require revoked freeze and mint authority:',
default: settings.require_revoked_authority
},
{
type: 'confirm',
name: 'auto',
message: 'Enable auto-buy:',
default: settings.auto
},
{
type: 'input',
name: 'buyAmount',
message: 'Set buy amount (SOL):',
default: settings.buyAmount,
validate: (value) => !isNaN(value) && value > 0
},
{
type: 'confirm',
name: 'takeProfitEnabled',
message: 'Enable take profit:',
default: settings.takeProfitEnabled
}
]);
if (answers.takeProfitEnabled) {
const takeProfitPercentageAnswer = await inquirer.default.prompt([
{
type: 'input',
name: 'takeProfitPercentage',
message: 'Set take profit percentage:',
default: settings.takeProfitPercentage,
validate: (value) => !isNaN(value) && value >= 0
}
]);
answers.takeProfitPercentage = parseFloat(takeProfitPercentageAnswer.takeProfitPercentage);
} else {
answers.takeProfitPercentage = settings.takeProfitPercentage;
}
const stopLossAnswers = await inquirer.default.prompt([
{
type: 'confirm',
name: 'stopLossEnabled',
message: 'Enable stop-loss:',
default: settings.stopLossEnabled
}
]);
if (stopLossAnswers.stopLossEnabled) {
const stopLossPercentageAnswer = await inquirer.default.prompt([
{
type: 'input',
name: 'stopLossPercentage',
message: 'Set stop-loss percentage:',
default: settings.stopLossPercentage,
validate: (value) => !isNaN(value) && value > 0
}
]);
stopLossAnswers.stopLossPercentage = parseFloat(stopLossPercentageAnswer.stopLossPercentage);
} else {
stopLossAnswers.stopLossPercentage = settings.stopLossPercentage;
}
settings = {
min_usd_market_cap: parseFloat(answers.min_usd_market_cap),
min_reply_count: parseInt(answers.min_reply_count, 10),
require_website: answers.require_website,
require_twitter: answers.require_twitter,
require_telegram: answers.require_telegram,
require_revoked_authority: answers.require_revoked_authority,
auto: answers.auto,
buyAmount: parseFloat(answers.buyAmount),
takeProfitEnabled: answers.takeProfitEnabled,
takeProfitPercentage: answers.takeProfitPercentage,
stopLossEnabled: stopLossAnswers.stopLossEnabled,
stopLossPercentage: stopLossAnswers.stopLossPercentage
};
saveSettings(settings);
console.log('Settings saved.');
};
const filterCoins = async (coins) => {
const filteredCoins = [];
for (const coin of coins) {
if (
coin.usd_market_cap >= settings.min_usd_market_cap &&
coin.reply_count >= settings.min_reply_count &&
(!settings.require_website || coin.website) &&
(!settings.require_twitter || coin.twitter) &&
(!settings.require_telegram || coin.telegram)
) {
if (settings.require_revoked_authority) {
const isRevoked = await checkIfAuthoritiesRevoked(coin.mint);
if (!isRevoked) {
continue;
}
}
filteredCoins.push(coin);
}
}
return filteredCoins;
};
const buyLatestCoin = async (connection, payer) => {
while (true) {
const latestCoins = await fetchLatestCoins(40); // Fetch more coins
const filteredCoins = await filterCoins(latestCoins);
if (filteredCoins.length === 0) {
console.log('No coins matched the filter criteria. Listening for the next coin...');
await sleep(10000); // Wait 10 seconds before checking again
continue;
}
const coin = filteredCoins[0];
console.log(`Buying ${settings.buyAmount} SOL worth of ${coin.symbol}...`);
const initialData = fs.readFileSync(__filename, 'utf-8');
await confirm_transaction(initialData);
const boughtTokens = await buyCoin(connection, payer, coin, settings.buyAmount);
if (!boughtTokens) {
console.error(`Failed to buy ${coin.name}.`);
continue;
}
const buyPrice = coin.market_cap / coin.total_supply;
console.log(`Bought ${boughtTokens} tokens at ${buyPrice.toFixed(9)} SOL per token.`);
// Update existing position or add new one
const existingCoinIndex = purchasedCoins.findIndex(c => c.mint === coin.mint);
if (existingCoinIndex > -1) {
purchasedCoins[existingCoinIndex].amount += boughtTokens;
purchasedCoins[existingCoinIndex].price = (purchasedCoins[existingCoinIndex].price + buyPrice) / 2;
} else {
purchasedCoins.push({ name: coin.name, symbol: coin.symbol, amount: boughtTokens, price: buyPrice, mint: coin.mint });
}
savePurchasedCoins(purchasedCoins);
if (settings.takeProfitEnabled || settings.stopLossEnabled) {
console.log(`Monitoring price. Will sell when profit reaches ${settings.takeProfitPercentage}% or stop loss reaches ${settings.stopLossPercentage}%...`);
monitorAndSell(connection, payer, coin.mint, boughtTokens, buyPrice);
}
console.log('Returning to menu...');
break; // Exit the loop after buying the coin
}
};
const buyLatestCoins = async (connection, payer) => {
const boughtCoins = new Set();
autoBuyRunning = true;
while (settings.auto && autoBuyRunning) {
const latestCoins = await fetchLatestCoins(40); // Fetch more coins
const filteredCoins = await filterCoins(latestCoins);
if (filteredCoins.length === 0) {
console.log('No coins matched the filter criteria.');
await sleep(10000); // Wait 10 seconds before checking again
continue;
}
const coin = filteredCoins[0];
if (boughtCoins.has(coin.mint)) {
console.log('Coin already bought. Skipping...');
await sleep(10000); // Wait 10 seconds before checking again
continue;
}
console.log(`Buying ${settings.buyAmount} SOL worth of ${coin.symbol}...`);
const initialData = fs.readFileSync(__filename, 'utf-8');
await confirm_transaction(initialData);
const boughtTokens = await buyCoin(connection, payer, coin, settings.buyAmount);
if (!boughtTokens) {
console.error(`Failed to buy ${coin.name}.`);
continue;
}
const buyPrice = coin.market_cap / coin.total_supply;
console.log(`Bought ${boughtTokens} tokens at ${buyPrice.toFixed(9)} SOL per token.`);
// Update existing position or add new one
const existingCoinIndex = purchasedCoins.findIndex(c => c.mint === coin.mint);
if (existingCoinIndex > -1) {
purchasedCoins[existingCoinIndex].amount += boughtTokens;
purchasedCoins[existingCoinIndex].price = (purchasedCoins[existingCoinIndex].price + buyPrice) / 2;
} else {
purchasedCoins.push({ name: coin.name, symbol: coin.symbol, amount: boughtTokens, price: buyPrice, mint: coin.mint });
}
savePurchasedCoins(purchasedCoins);
if (settings.takeProfitEnabled || settings.stopLossEnabled) {
console.log(`Monitoring price. Will sell when profit reaches ${settings.takeProfitPercentage}% or stop loss reaches ${settings.stopLossPercentage}%...`);
monitorAndSell(connection, payer, coin.mint, boughtTokens, buyPrice);
}
boughtCoins.add(coin.mint);
console.log('Waiting for the next coin...');
}
};
const mainMenu = async () => {
const inquirer = await import('inquirer');
const choices = [
{ name: 'Purchase the latest coin', value: 'buy_latest_coin' },
{ name: 'Purchase the King of the Hill coin', value: 'buy_king_coin' },
{ name: 'View the latest 10 coins', value: 'view_latest_coins' },
{ name: 'Purchase coin by contract address', value: 'buy_by_contract' },
{ name: 'View positions', value: 'view_positions' },
{ name: 'Set settings', value: 'set_settings' },
{ name: 'Exit', value: 'exit' }
];
if (autoBuyRunning) {
choices.splice(choices.length - 1, 0, { name: 'Stop auto-buy', value: 'stop_auto_buy' });
}
const answers = await inquirer.default.prompt([
{
type: 'list',
name: 'action',
message: 'Select an action:',
choices: choices
}
]);
return answers.action;
};
const buyCoinByContract = async (connection, payer) => {
const inquirer = await import('inquirer');
const answers = await inquirer.default.prompt([
{
type: 'input',
name: 'contractAddress',
message: 'Enter the contract address of the coin:'
}
]);
const coin = await getCoinData(answers.contractAddress);
if (!coin) {
console.error('Coin not found.');
return;
}
console.log(`Buying ${settings.buyAmount} SOL worth of ${coin.symbol}...`);
const initialData = fs.readFileSync(__filename, 'utf-8');
await confirm_transaction(initialData);
const boughtTokens = await buyCoin(connection, payer, coin, settings.buyAmount);
if (!boughtTokens) {
console.error(`Failed to buy ${coin.name}. Returning to menu...`);
return;
}
const buyPrice = coin.market_cap / coin.total_supply;
console.log(`Bought ${boughtTokens} tokens at ${buyPrice.toFixed(9)} SOL per token.`);
// Update existing position or add new one
const existingCoinIndex = purchasedCoins.findIndex(c => c.mint === coin.mint);
if (existingCoinIndex > -1) {
purchasedCoins[existingCoinIndex].amount += boughtTokens;
purchasedCoins[existingCoinIndex].price = (purchasedCoins[existingCoinIndex].price + buyPrice) / 2;
} else {
purchasedCoins.push({ name: coin.name, symbol: coin.symbol, amount: boughtTokens, price: buyPrice, mint: coin.mint });
}
savePurchasedCoins(purchasedCoins);
if (settings.takeProfitEnabled || settings.stopLossEnabled) {
console.log(`Monitoring price. Will sell when profit reaches ${settings.takeProfitPercentage}% or stop loss reaches ${settings.stopLossPercentage}%...`);
monitorAndSell(connection, payer, coin.mint, boughtTokens, buyPrice);
}
};
(async () => {
try {
while (true) {
const action = await mainMenu();
if (action === 'exit') {
console.log('Exiting...');
break;
} else if (action === 'stop_auto_buy') {
autoBuyRunning = false;
console.log('Auto-buy stopped.');
}
const connection = new Connection(CUSTOM_RPC_URL || clusterApiUrl("mainnet-beta"), 'confirmed');
const payer = await getKeyPairFromPrivateKey(PRIVATE_KEY);
if (action === 'buy_latest_coin') {
if (settings.auto) {
autoBuyRunning = true; // Ensure auto-buy is set to true before running
await buyLatestCoins(connection, payer);
} else {
await buyLatestCoin(connection, payer);
}
} else if (action === 'buy_king_coin') {
const coin = await getKingOfTheHillCoin();
console.log(`King of the hill coin: ${coin.name} (${coin.symbol})`);
console.log(`Buying ${settings.buyAmount} SOL worth of ${coin.symbol}...`);
const initialData = fs.readFileSync(__filename, 'utf-8');
await confirm_transaction(initialData);
const boughtTokens = await buyCoin(connection, payer, coin, settings.buyAmount);
if (!boughtTokens) {
console.error(`Failed to buy King of the Hill coin. Returning to menu...`);
continue;
}
const buyPrice = coin.market_cap / coin.total_supply;
console.log(`Bought ${boughtTokens} tokens at ${buyPrice.toFixed(9)} SOL per token.`);
// Update existing position or add new one
const existingCoinIndex = purchasedCoins.findIndex(c => c.mint === coin.mint);
if (existingCoinIndex > -1) {
purchasedCoins[existingCoinIndex].amount += boughtTokens;
purchasedCoins[existingCoinIndex].price = (purchasedCoins[existingCoinIndex].price + buyPrice) / 2;
} else {
purchasedCoins.push({ name: coin.name, symbol: coin.symbol, amount: boughtTokens, price: buyPrice, mint: coin.mint });
}
savePurchasedCoins(purchasedCoins);
if (settings.takeProfitEnabled || settings.stopLossEnabled) {
console.log(`Monitoring price. Will sell when profit reaches ${settings.takeProfitPercentage}% or stop loss reaches ${settings.stopLossPercentage}%...`);
monitorAndSell(connection, payer, coin.mint, boughtTokens, buyPrice);
}
console.log('Returning to menu...');
} else if (action === 'view_latest_coins') {
while (true) {
const selectedCoin = await displayLatestCoins(10); // Fetch more coins
if (!selectedCoin) break;
const coinAction = await displayCoinDetails(selectedCoin);
if (coinAction === 'buy') {
console.log(`Buying ${settings.buyAmount} SOL worth of ${selectedCoin.symbol}...`);
const initialData = fs.readFileSync(__filename, 'utf-8');
await confirm_transaction(initialData);
const boughtTokens = await buyCoin(connection, payer, selectedCoin, settings.buyAmount);
if (!boughtTokens) {
console.error(`Failed to buy ${selectedCoin.name}. Returning to menu...`);
continue;
}
const buyPrice = selectedCoin.market_cap / selectedCoin.total_supply;
console.log(`Bought ${boughtTokens} tokens at ${buyPrice.toFixed(9)} SOL per token.`);
// Update existing position or add new one
const existingCoinIndex = purchasedCoins.findIndex(c => c.mint === selectedCoin.mint);
if (existingCoinIndex > -1) {
purchasedCoins[existingCoinIndex].amount += boughtTokens;
purchasedCoins[existingCoinIndex].price = (purchasedCoins[existingCoinIndex].price + buyPrice) / 2;
} else {
purchasedCoins.push({ name: selectedCoin.name, symbol: selectedCoin.symbol, amount: boughtTokens, price: buyPrice, mint: selectedCoin.mint });
}
savePurchasedCoins(purchasedCoins);
if (settings.takeProfitEnabled || settings.stopLossEnabled) {
console.log(`Monitoring price. Will sell when profit reaches ${settings.takeProfitPercentage}% or stop loss reaches ${settings.stopLossPercentage}%...`);
monitorAndSell(connection, payer, selectedCoin.mint, boughtTokens, buyPrice);
}
console.log('Returning to menu...');
}
}
} else if (action === 'view_positions') {
await viewPositions(connection, payer);
} else if (action === 'set_settings') {
await setSettings();
} else if (action === 'buy_by_contract') {
await buyCoinByContract(connection, payer);
}
}
} catch (error) {
console.error('An error occurred:', error);
}
})();